每当单元格值更新时,如何触发Excel VBAmacros?

我有一个小组,我想运行时更新单元格包含一个特定的值。

现在我正在使用如下代码:

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range) If Target.Cells.Count = 1 Then If Target.Value = XYZ Then my_sub a, b, c End If End If End Sub 

现在的问题是macros只在我直接编辑这些单元格时触发,而不是在其他单元格中的更改迫使这些单元格改变时触发。

此外,这些细胞没有很好的定义,所以我不能硬编码“当A5改变”,例如。 每次当我的工作簿中的任何单元格更新(手动或通过公式),以满足我的条件,我需要这个。

如果你的目标只是一个需要被监控的公式的单个单元格,这将起作用:

 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 
  1. 将要跟踪的单元添加到指定的公式(命名的范围)。 我用了rngValue
  2. 使用一个静态variables来跟踪你想跟踪的值在这个范围内发生的次数
  3. 使用Calculate事件来检查发生次数是否发生变化

 Private Sub Worksheet_Calculate() Dim StrIn As String Static lngCnt As Long Dim lngCnt2 As Long StrIn = "apples" lngCnt2 = Application.WorksheetFunction.CountIf(Range("rngValue"), StrIn) If lngCnt2 <> lngCnt Then lngCnt = lngCnt2 Call mysub End If End Sub 

目标是一个可以包含更多细胞的范围。 这个代码应该适合你。

 Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range) For Each cell In Target.Cells If cell.Value = XYZ Then my_sub a, b, c End If Next cell End Sub 

编辑:我看到你也想在公式更新定义值时触发。 如果您检查每个单元格,速度可能会很慢,但实际上取决于文件的大小。 这里有一些代码给你想法如何做到这一点。

 Private Sub Workbook_SheetCalculate(ByVal sh As Object) For Each cell In sh.Cells.SpecialCells(xlCellTypeFormulas).Cells If cell.Value = XYZ Then my_sub a, b, c End If Next cell End Sub