简体   繁体   中英

How to control VBA to only allow 1 instance of application.ontime to run

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM