在TimerProc每X秒完成一次之后运行其他子项目(Excel VBA中的API SetTimer)



我正在将excel中的Windows API计时器用于VBA项目(有点像VBA的初学者),在调查Excel为什么不断崩溃时,我想到了这个问题。

在具有多个 sub 的宏中,第一个 sub 启动计时器,该计时器将运行 TimerProc 代码,例如每 5 秒一次。启动计时器后,第一个子完成,下一个开始。其他函数在第二个子中调用,程序在达到计时器上的 5 秒之前完成。因此,从技术上讲,整个宏在调用 TimerProc 时已经完成。

此时,是否可以在 TimerProc 代码结束后运行/调用任何其他子或函数的任何其他部分?显然,您可以在TimerProc代码中进行调用,但是在它结束后呢?例如,如果在 TimerProc 中执行 KillTimer ,但我没有在 TimerProc 中重新启动计时器,有没有办法在其他地方重新启动计时器?

注意:我正在使用调用 Windows 计时器的方法,详见 http://www.cpearson.com/excel/OnTime.aspx

尝试的示例:

Public Declare Function SetTimer Lib "user32" ( _
ByVal HWnd As Long, _
ByVal nIDEvent As Long, _
ByVal uElapse As Long, _
ByVal lpTimerFunc As Long) As Long
Public Declare Function KillTimer Lib "user32" ( _
ByVal HWnd As Long, _
ByVal nIDEvent As Long) As Long
Public TimerID As Long
Public TimerSeconds As Single
Sub StartTimer()
TimerSeconds = 10000 ' how often to "pop" the timer, in milliseconds
TimerID = SetTimer(0&, 0&, TimerSeconds, AddressOf TimerProc)
End Sub
Sub EndTimer()
'On Error Resume Next
KillTimer 0&, TimerID
End Sub
Sub TimerProc(ByVal HWnd As Long, ByVal uMsg As Long, _
ByVal nIDEvent As Long, ByVal dwTimer As Long)
timerFinished = True
Call EndTimer
'Instead of calling StartTimer here inside TimerProc, I want to exit TimerProc and re-run the below sub, which will now call StartTimer
End Sub

Sub exampleSub ()
Call StartTimer
If timerFinished = True Then
Msgbox "It worked!"
call StartTimer
End If        
End Sub

计时器当前设置为 10 秒,示例 Sub 肯定会在该 10 秒命中之前完成运行,并且 TimerProc 能够运行并将 timerFinished 布尔值更改为 True。有没有办法,一旦TimerProc完成,重新运行exampleSub(现在timerDone是True)来重新启动计时器,而无需在TimerProc本身中调用StartTime?我想确保计时器Proc完全结束。

要在TimerProc完成后启动exampleSub,您可以使用:

Application.OnTime Now, "exampleSub"

上面的语句指示 VBA 在当前处理(当前在调用堆栈中的所有例程)完成后尽快启动exampleSub

顺便说一下,您可以使用Application.OnTime循环来解决原始问题,而无需SetTimerAPI。后者仅在您需要以毫秒为单位的计时时才有趣,而OnTime单位是一秒。

最新更新