简体   繁体   English

如何控制VBA仅允许1个application.ontime实例运行

[英]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. 我有一个使用application.ontime的时间循环,该循环每隔5分钟将一个单元工作簿中的单元格块复制并粘贴到另一个工作簿中。 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: 到目前为止,我的application.ontime中包含以下内容:

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. 假设我在6:30 pm启动一个实例...直到9pm都可以正常工作,然后我开始获取副本。 When I break the VBA, I get three pop up errors instead of one, confirming that there are multiple instances of it running. 破坏VBA时,出现三个弹出错误,而不是一个,确认有多个实例正在运行。 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? 可能是我昨天晚上9点启动了application.ontime并重新启动了吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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