我正在尝试从某个时间点到某个结束时间点以非常短的间隔(例如每秒)运行某个宏。这意味着我需要一个起点和一个截止点。我无法使用 Workbook_Open() Event
,因为我已经在工作簿打开后的不同时间触发了其他宏。
我用来每秒触发一次宏的基本行是这个伪代码:
Application.OnTime Now + TimeValue("00:00:01"), "Path to Macro"
从我到目前为止的实验来看,我所做的任何尝试都以两个结果告终。在第一种情况下,它从我打开工作簿的那一刻开始运行,并以每秒一次的适当时间表运行。但是,第一种情况不是最理想的,因为我需要它在启动之前稍等片刻。在第二种情况下,它在我希望它启动的时候运行——但它只运行了一次,这也不是我想要发生的。
总结一下:
我需要类似代码行的东西,以便在工作簿打开 15 分钟后开始运行,并在 3 小时后停止。
最佳答案
从 workbook_open 启动了哪些其他定时宏,为什么这些会干扰?听起来你在不必要地限制自己。以下是解决问题的方法:
Workbook_open 应该使用 application.ontime 来调用通用函数 do_timed_events。 do_timed_events 函数应该在每次运行时使用 application.ontime 重新添加自己。它还应该跟踪状态。对于它的前几次运行,它应该执行其他特定任务,然后等待 15m,然后开始执行每秒任务。
这是一些伪代码:
private var do_timed_events_state as string
sub do_timed_events
if do_timed_events_state = "" then
do_task_1(arg1,arg2)
do_timed_events_state = "task_2"
Application.OnTime Now + TimeValue("00:00:01"), "do_timed_events"
elseif do_timed_events_state = "task_2" then
do_timed_events_state = "repeating_task"
Application.OnTime Now + TimeValue("00:00:01"), "do_timed_events"
elseif do_timed_events_state = "repeating_task" then
Application.OnTime Now + TimeValue("00:00:01"), "do_timed_events"
end if
end sub
你可能会想出一个比我更好的设计。
关于Excel VBA : Application. OnTime 未正确执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2646635/