VBA: Reliable timing with Application.OnTime?

2k Views Asked by At

I need to run a large procedure (RunLargeSub) every second, and this procedure takes about 0.5s to complete. I'm currently using Application.OnTime, but won't this result in RunLargeSub being called every ~1.5s ? Is it possible to fix this to 1.0s?

Sub Update()
    RunLargeSub
    NextTick = Now + TimeValue("00:00:01")
    Application.OnTime NextTick, "Update"
End Sub


Sub Stop()
    On Error Resume Next
    Application.OnTime NextTick, "UpdateClock", , False
    On Error GoTo 0
End Sub

All help much appreciated.

1

There are 1 best solutions below

0
On

You declare NextTick after RunLargeSub. Thats why it takes 1.5s. If you declare it before RunLargeSub it will take exactly 1s. But then you'll have problem if RunLargeSub takes more then 1s because the main sub will stop executing. I'm not sure if onTime accepts fractions of a second but you can do that:

Sub Update()
    RunLargeSub
    NextTick = Now + TimeValue("00:00:01")/2
    Application.OnTime NextTick, "Update"
End Sub

It should run RunLargeSub and in half a second will call the sub again.