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

前端 未结 2 909
温柔的废话
温柔的废话 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:43

    You can "temporarily UnDo" to retrieve the original value:

    Private Sub Worksheet_Change(ByVal Target As Range)
       Dim Where As String, Oldvalue As Variant, NewValue As Variant
       Application.EnableEvents = False
          Where = Target.Address
          NewValue = Target.Value
          Application.Undo
          Oldvalue = Target.Value
          Target.Value = NewValue
       Application.EnableEvents = True
    
       MsgBox Where & vbCrLf & Oldvalue & vbCrLf & NewValue
    End Sub
    

    This is only good for single cells.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题