VBA 运行代码不停

VBA Run Code non-stop

我正在尝试编写一个无限期运行的程序,直到我停止它。由于某种原因,它提前退出了这个 while 循环(6 小时后)。一位同事认为这是因为 cpu 中的错误,我应该使用布尔标志而不是字符串(错误的可能性较小)。还有其他建议吗?

If CommandButton1.Caption = "Start" Then
    CommandButton1.Caption = "Stop"
Else
    CommandButton1.Caption = "Start"
End If


While CommandButton1.Caption = "Stop"
    pause 1
    Range("C1").Value = Range("C1").Value + 1
    If Range("C1").Value = 300 Then
        Range("C1").Value = 0
        takeameasurement      ' This function did not cause the problem
    End If
Wend

(如果你想知道我的暂停功能)

Function pause(time As Integer)
t = Timer + time      'wait for the table to settle before taking a measurement

Do While t > Timer
    DoEvents
Loop
End Function

计时器 returns 自午夜以来的秒数,因此如果您在计时器循环回到零之前调用 pause 函数,您可能 运行 会遇到问题。

想象一天只有 100 秒,当 Timer = 99.5 时调用 pause - 最终可能会得到 t 的值,即 100.5,在这种情况下 t > Timer 将永远为真,您的 Do 循环永远不会退出。

Function pause(time As Integer)
    t = Timer + time      

    Do While t > Timer
        DoEvents
    Loop
End Function