Excel Worksheet_Change not triggering with cell value update

946 views Asked by At

I´ve done some extensive research, but cannot solve my problem. I have an Excel workbook where I constantly pull a value from an OPC server. The value is stored in a set of rows. This works perfectly whenever I introduce the data manually, but when the cell is automatically updated, it does not work.

    Private Sub Worksheet_Change(ByVal target As Range)
    'MsgBox = Target.Address
    If Not Application.Intersect(Range("B1:B2"), Range(target.Address)) Is Nothing Then
        Call CopyDataToRecord
    End If
End Sub

Sub CopyDataToRecord()

    Dim IndexI As Integer
    Dim IndexY As Integer
    Dim IndexMius As Integer
    Dim DufferLength As Integer
    
    DufferLength = 20
    IndexY = DufferLength + 5
    
    'Shift Data
    For IndexI = i To DufferLength
        IndexYMius = IndexY - 1
        Cells(IndexY, 1) = Cells(IndexYMius, 1)
        Cells(IndexY, 2) = Cells(IndexYMius, 2)
        IndexY = IndexYMius
    Next IndexI
    
    'Copy The Latest Data
    Range("A2:B2").Copy Range("A5:B5")
End Sub

enter image description here

2

There are 2 answers

0
Jean-Paul On

Your code (a bit adapted to declare i and IndexYMius) works well on my Excel sheet. I would just recommend to prevent recursive Worksheet_Change calls by protecting the changes with Application.EnableEvents:

Private Sub Worksheet_Change(ByVal target As Range)
    'MsgBox = Target.Address
    If Not Application.Intersect(Range("B1:B2"), Range(target.Address)) Is Nothing Then
        Application.EnableEvents = False
        Call CopyDataToRecord
        Application.EnableEvents = True
    End If
End Sub
0
Jean-Paul On

BTW, if your code is not triggered by the automatic update process, it might be because this process includes somewhere an Application.EnableEvents = False that prevents the Worksheet_Change to be executed.