使用VBA如何检测工作表中的任何值何时更改?

我有一个包含数百个值的几列的工作表。 我希望单元格A1在工作表中的任何值发生更改时立即说出“值已更改”。 我试图做一些代码就像你在下面看到的,但我想不出如何捕获OriginalValuevariables中的原始值。 如何检测任何单元格中的值是否与目标值不同?

Private Sub Worksheet_Change(ByVal Target As Range) If Target.Value <> OriginalValue Then Range("A1").Value = "Value Change" End If End Sub 

继续我的评论看到这一点。 我已经评论了代码,所以你不会理解它的问题。 但是,如果你这样做,然后只是问。 🙂

 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 

你可以“暂时不做”来检索原始值:

 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 

这仅适用于单体电池。