Search code examples
exceltimerontimevba

Excel VBA: Application.OnTime Not Executing Properly


I am trying to run a certain macro in very short intervals, such as every second, from a certain point in time until a certain end point in time. This means I need a starting point and a cutoff point. I cannot use the Workbook_Open() Event, since I already have other macros triggering at different times after the opening of the Workbook.

The basic line I use to trigger the Macro once a second is this psuedocode:

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

From my experiments so far, any attempt I made ended up with two results. In the first case, it ran from the moment I opened the Workbook and with the appropriate schedule of once per second. However, the first case was suboptimal, as I needed it to wait a bit before it started up. In the second case, it ran at the time I wanted it to start - but it ran only once, which was also not what I wanted to happen.

To summarize:

I need something like the code line to start running 15 minutes after the Workbook is opened and stop 3 hours later.


Solution

  • What other timed macros are started from workbook_open, and why are these interfering? It sounds like you're limiting yourself unnecessarily. Here's how to address the issue:

    Workbook_open should use application.ontime to call a general function do_timed_events. The do_timed_events function should re-add itself using application.ontime each time it is run. It should also keep track of state. For its first few runs, it should perform the other specific tasks, then wait 15m, then start performing the every-second task.

    Here's some pseudocode:

    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
    

    You can probably come up with a better design than me on this one.