需要VBA使Excel能够实时和在后台计算工作表或范围

时间:2009-05-15 20:31:23

标签: excel vba excel-vba

如何让Excel连续实时计算工作表/范围(不是1 calc / sec)并在后台进行?

我希望这个指标时钟像秒表一样运行....

  

=IF(LEN(ROUND((HOUR(NOW())*(100/24)),0))=1,"0"&ROUND((HOUR(NOW())*(100/24)),0),ROUND((HOUR(NOW())*(100/24)),0))&":"&IF(LEN(ROUND((MINUTE(NOW())*(100/60)),0))=1,"0"&ROUND((MINUTE(NOW())*(100/60)),0),ROUND((MINUTE(NOW())*(100/60)),0))&":"&IF(LEN(ROUND((SECOND(NOW())*(100/60)),0))=1,"0"&ROUND((SECOND(NOW())*(100/60)),0),ROUND((SECOND(NOW())*(100/60)),0))

2 个答案:

答案 0 :(得分:2)

我认为这可能会使你的“(不是1次计算/秒)”标准失败,但我取得了类似的结果如下。假设您的公式位于名为Sheet1的工作表的单元格A1中。

在ThisWorkbook代码模块中:

Private Sub Workbook_Open()
    Application.OnTime Now + TimeValue("00:00:01"), "RecalculateRange"
End Sub

...并在常规代码模块中:

Public Sub RecalculateRange()
    Sheet1.Range("A1").Calculate
    Application.OnTime Now + TimeValue("00:00:01"), "RecalculateRange"
End Sub

答案 1 :(得分:2)

我已经使用以下内容来产生您正在寻找的效果:

Option Explicit

Public TimerRunning As Boolean
Dim CalculationDelay As Integer

Public Sub StartStop_Click()
    If (TimerRunning) Then
        TimerRunning = False
    Else
        TimerRunning = True
        TimerLoop
    End If
End Sub

Private Sub TimerLoop()
    Do While TimerRunning
        '// tweak this value to change how often the calculation is performed '
        If (CalculationDelay > 500) Then
            CalculationDelay = 0
            Application.Calculate
        Else
            CalculationDelay = CalculationDelay + 1
        End If
        DoEvents
    Loop
End Sub

StartStop_Click是我与秒表的开始/停止按钮关联的宏。您可以获得幻想,并根据TimerRunning的值将其名称更改为“开始”或“停止”,但我保持简单以说明概念。

这里的两个关键事项是:

Application.Calculate

强制Excel计算工作表,并且:

DoEvents

允许VBA在后台运行(即Excel不会停止响应用户输入)。即使计时器正在运行,这也可以让您按下“停止”按钮。