Using VBA how do I detect when any value in a worksheet changes?

前端 未结 2 968
温柔的废话
温柔的废话 2021-01-24 05:00

I have a worksheet that contains a few columns with hundreds of values. I want cell A1 to say \"Value Changed\" as soon as any value changes in the worksheet. I tried to make so

2条回答
  •  灰色年华
    2021-01-24 05:46

    Further to my comments see this. I have commented the code so you will not have a problem understanding it. But if you do then simply ask. :)

    Dim PrevValue As Variant
    
    Private Sub Worksheet_Change(ByVal Target As Range)
    
        '~~> Check if more than 1 cell is changed
        If Target.Cells.CountLarge > 1 Then Exit Sub
    
        '~~> Check if the change didn't happen in A1
        If Not Intersect(Target, Range("A1")) Is Nothing Then Exit Sub
    
        On Error GoTo Whoa
    
        Application.EnableEvents = False
    
        '~~> Compare
        If Target.Value <> PrevValue Then
            Range("A1").Value = "Value of " & Target.Address & " changed from " & _
                                PrevValue & " to " & Target.Value
    
            '~~> Store new value to previous value
            PrevValue = Target.Value
        End If
    
    Letscontinue:
        Application.EnableEvents = True
        Exit Sub
    Whoa:
        MsgBox Err.Description
        Resume Letscontinue
    End Sub
    
    Private Sub Worksheet_SelectionChange(ByVal Target As Range)
        PrevValue = Target.Value
    End Sub
    

提交回复
热议问题