提供你的目标是仅与需要监测的公式单个细胞,这将工作:
Option Explicit
Dim tarVal As Variant
Private Sub Worksheet_Activate()
tarVal = ActiveSheet.Range("A1").Value ' change range parameter to the address of the target formula
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
Dim tempVal As Variant
tempVal = ActiveSheet.Range("A1").Value
If tempVal <> tarVal Then
tarVal = tempVal
' your code here
MsgBox "The value of A1 has changed" ' for testing purposes only, delete later
End If
End Sub
编辑
下面的代码适用于细胞的整个范围,但只有在自动计算打开的情况下。如果监视的单元格不连续,则只需在定义目标范围时使用union语句。 (在本例中,目标范围是A1:A10)。这是假设目标范围内只有一个公式可以一次更改其值。如果多个目标公式可以做到这一点,则删除Worksheet_Change
子程序中的Exit for
。
Option Explicit
Dim tarCellCount As Long
Dim tarRng As Range
Dim tarVals As Variant
Private Sub Worksheet_Activate()
Dim i As Long
Dim cll As Range
Set tarRng = ActiveSheet.Range("A1:A10") ' change range parameter to the addresses of the target formulas
tarCellCount = tarRng.Cells.count
ReDim tarVals(1 To tarCellCount) As Variant
For Each cll In tarRng
i = i + 1
tarVals(i) = cll.Value
Next cll
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
Dim changeBool As Boolean
Dim i As Long
Dim cll As Range
Dim tempVal As Variant
For Each cll In tarRng
tempVal = cll.Value
i = i + 1
If tempVal <> tarVals(i) Then
tarVals(i) = tempVal
changeBool = True
Exit For
End If
Next cll
If changeBool Then
' your code here
MsgBox "The value of one of the cells in the target range has changed" ' for testing purposes only, delete later
End If
End Sub
究竟是不是在这里工作?这是事实,这不能捕捉公式的变化?在这种情况下,查看“Worksheet.Calculate'事件(https://msdn.microsoft.com/en-us/library/office/ff838823.aspx)。 – Mikegrann
此外,只要确保你的代码不是你实际使用的 - 如果是,你是否想'如果target.value =“XYZ”'?什么不适用于宏? – BruceWayne
它仅在我直接编辑单元格时触发,而不是在其他单元格中的更改强制更改时触发。我不知道如何使它与Worksheet.Calculate一起工作,因为没有Target参数。不,这不是代码,所以XYZ上的引号不是问题 – user1923052