while循环-VBA不间断地运行代码



我正试图编写一个无限期运行的程序,直到我停止它。由于某种原因,它提前(6小时后(退出了while循环。一位同事认为这是因为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

Timer返回自午夜以来的秒数,因此如果在Timer循环回零之前调用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

相关内容

最新更新