如何在活动中创建一个计数器?

B C*_*ung 3 excel events vba excel-vba excel-2013

在Cell A1中,我有一个每隔一到两秒自动重新计算的公式.当此单元格重新计算时,A1中的旧值将复制到单元格B1.每次重新计算时,我只想获得一个总计.到目前为止,有效的是当A1发生变化时,旧值被复制到B1,但每次执行此操作时都无法获得运行总计.问题是i总是等于1.任何想法?

Private Sub Worksheet_Calculate()
    Dim dProfit As Double
    Dim i As Integer

    dProfit = Me.Range("A1").Value
    Application.EnableEvents = False

    If dProfit >= 1 Then
        i = i + 1
        MsgBox "calculation detected is " & dProfit & " i= " & i
        Range("$B1") = dProfit
        Application.EnableEvents = True
    End If
End Sub
Run Code Online (Sandbox Code Playgroud)

L42*_*L42 5

尝试i在sub之外声明.

Dim i As Integer

Private Sub Worksheet_Calculate()
' Rest of your code here
End Sub
Run Code Online (Sandbox Code Playgroud)

这种方式变量i将在子终止后保持不变.
只要VBA不停止或遇到错误,它就会持续存在.