Reputation: 1354
I have a time loop using application.ontime
which copy and paste blocks of cells from one workbook to another workbook every 5 minutes. From time to time it will copy and paste duplicates, making me suspect that there are multiple instances of it running. Is there a way to prevent multiple version of it running at once? Or is there a way to check how many instances of it is running (pending) at a particular time?
What I have so far in my application.ontime
is the following:
Sub timer()
If Hour(Time) <= 16 Or Hour(Time) >= 18 Then
Application.OnTime TimeSerial(Hour(Time), Application.WorksheetFunction.Floor(Minute(Time), 5), 0) + TimeValue("00:05:00"), "dataextract", , True
End If
End Sub
Secondary question: I don't particularly understand how it works in rich detail. Say I start an instance at 6:30pm... it works fine until 9pm and then I start getting duplicates. When I break the VBA, I get three pop up errors instead of one, confirming that there are multiple instances of it running. However I don't understand what could have caused it to duplicate? Could it be that I initiated application.ontime yesterday at 9pm and it restarted itself?
Upvotes: 0
Views: 662
Reputation:
You could store the scheduled time and cancel the previous schedule before creating the next schedule task.
On Error Resume Next
Application.OnTime EarliestTime:=Range("NextSchedule"), Procedure:="dataextract", Schedule:=False
On Error GoTo 0
Range("NextSchedule") = TimeSerial(Hour(Now), Application.WorksheetFunction.Floor(Minute(Time), 5) + 5, 0)
Application.OnTime EarliestTime:=Range("NextSchedule"), Procedure:="dataextract", Schedule:=True
Upvotes: 1