提供你的目標是僅與需要監測的公式單個細胞,這將工作:
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