Excel VBA中监听单元格更改的最佳方法

我正在试图观察一个细胞的变化。 这个单元格可以每隔一秒钟由一些添加的VBA代码触发一次,我想要增加值的更新次数。

我到目前为止是:

Private Sub Worksheet_Calculate() Static oldval If Range("C3").Value <> oldval Then oldval = Range("C1").Value Blad1.Range("N18").Value = Blad1.Range("N18").Value + 1 End If End Sub 

问题是,当我开始我的Excel工作表时,代码崩溃一次错误: Out of stack space

我的问题是现在为什么我得到这个错误,这是我想要做什么的fastes实现?

关于StackOverflow上堆栈溢出的问题。

递增计数器单元会触发Calculate事件,这会增加触发计算事件的计数器等。使用另一个静态variables来防止recursion。 一个静态variables通过对托pipe它的过程的调用保持其值。

 Private Sub Worksheet_Calculate() Static bWorking as Boolean Static oldval As Variant If Not bWorking Then If Range("C3").Value <> oldval Then oldval = Range("C1").Value bWorking = True Blad1.Range("N18").Value = Blad1.Range("N18").Value + 1 bWorking = False End If End If End Sub 

另外考虑@YowE3的评论,为什么你的代码将oldval设置为C1的值。

编辑 :至于你的问题的性能部分,假设你想要将计数器的值存储到实时单元格中,可以通过重新使用单元格引用,将计数保持在一个静态variables中,并使用Value2属性。

 Private Sub Worksheet_Calculate() Static monitoredCell As Excel.Range Static counterCell As Excel.Range Static counter As Long Static bWorking As Boolean Static oldVal As Variant If Not bWorking Then If monitoredCell Is Nothing Then 'Initialize the ranges. Set monitoredCell = Me.Range("C3") Set counterCell = Blad1.Range("N18") 'Comment out the line below if you don't wish to keep counting from the last saved value. counter = counterCell.Value2 End If If monitoredCell.Value2 <> oldVal Then oldVal = monitoredCell.Value2 counter = counter + 1 bWorking = True counterCell.Value2 = counter bWorking = False End If End If End Sub