2010-04-15 393 views
2

我试图从一个特定的时间点到特定的结束时间点,以非常短的时间间隔(例如每秒)运行某个宏。这意味着我需要一个起点和一个截止点。我不能使用Workbook_Open() Event,因为在打开工作簿之后,我已经在不同时间触发了其他宏。Excel VBA:Application.OnTime没有正确执行

的基本路线,我用它来触发宏一次,第二次是这样的伪代码:

Application.OnTime Now + TimeValue("00:00:01"), "Path to Macro" 

从我的实验,到目前为止,任何企图我做结束了两个结果。在第一种情况下,它从我打开工作簿的那一刻开始,并按照每秒一次的适当时间表运行。但是,第一个案例并不理想,因为我需要它在启动之前稍微等一下。在第二种情况下,它在我想要开始的时候运行 - 但它只运行一次,这也不是我想要发生的事情。

总结:

我需要类似的代码行打开工作簿后开始运行15分钟,停3个小时后。

回答

1

其他的定时宏是从workbook_open启动的,为什么这些干扰会影响?这听起来像是你不必要地限制自己。以下是解决问题的方法:

Workbook_open应该使用application.ontime来调用一个通用函数do_timed_events。 do_timed_events函数应该在每次运行时使用application.ontime重新添加自己。它也应该跟踪状态。对于它的前几次运行,它应该执行其他特定任务,然后等待15米,然后开始执行每秒的任务。

下面是一些伪代码:

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 

你或许可以拿出一个比我在这一个更好的设计。

+0

非常感谢K. Robinson,这是一个很好的解决方案,我会在周末后实施它,但它似乎很有意义。我必须说我完全忘记了使用自称的例程。自从我上次处理代码以来已经有一段时间了。再次感谢你。我喜欢这个网站! – Yaron 2010-04-16 16:39:45