Excel VBA: Application.OnTime Not Executing Properly - excel

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.

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.

Related

Excel Application on Time method doesn't work properly

I would like to automatize scheduled report on my company. I found out a method called Application OnTime in Excel, which after some reading looks like a perfect match.
The task is following, on chosen periods during day I would like to import data through powerquery and then save a file. I would like to work it all the time. My simple code looks like that:
Private Sub Workbook_Open()
Application.OnTime TimeValue("06:30:00"), "Module1.MyMacro"
Application.OnTime TimeValue("09:30:00"), "Module1.MyMacro"
Application.OnTime TimeValue("12:00:00"), "Module1.MyMacro"
Application.OnTime TimeValue("14:29:00"), "Module1.MyMacro"
End Sub
Sub MyMacro()
ActiveWorkbook.RefreshAll
Application.Wait (Now + TimeValue("0:05:00"))
ActiveWorkbook.Save
End Sub
Due to overlong refresh of the data I gave extra 5 mins before saving file. However I encountered problem, after some time my script stops working. I have tried different solutions from the Internet, unfortunately I couldn't complete the task on my own.
I have a request If someone could tell me abaout what I've forgotten and explain the issue.
The first parameter is EarliestTime. Your post lack some detail, but I guess it'll start a bit late. The third parameter is LatestTime. Try something like this:
Application.OnTime TimeValue("06:30:00"), "Module1.MyMacro", TimeValue("06:40:00")
https://learn.microsoft.com/en-us/office/vba/api/excel.application.ontime

Bloomberg stops VBA Application.Ontime

I have the following VBA subroutine which is calls itself every second:
Public Sub AllTheTime()
iTimerSet = Now + TimeValue("00:00:01")
Call runMyFunction
Application.OnTime iTimerSet, "AllTheTime"
End Sub
This script is running perfectly: It is recalling itself every second and calculating some stuff.
But when I install the Bloomberg Office Add-On (Bloomberg Ribbon) it is no longer working: It is running exactly one time then it is stopped. I checked this with Debug.Print. It seems that Bloomberg is stopping the "Application.OnTime" method.
Do you have any ideas what causes this behaviour?

How to run VBA Excel macro at a specific time and then every 2 hours thereafter

I would like a VBA Excel macro to run every morning # 8:30AM and then every 2 hours thereafter with the final one # 4:30pm (10:30am, 12:30pm, 2:30pm,4:30pm).
I have the following two scripts so far, however cannot seem to figure out how to have it start # 8:30AM:
Private Sub Workbook_Open()
Call SetTimeToRun
End Sub
Private Sub SetTimeToRun()
Application.OnTime Now() + TimeValue("02:00:00"), "LiveBook"
End Sub
If you want to run it a specific amount eg 3 times then simply do:
Application.OnTime Now() + TimeValue("02:00:00"), "LiveBook"
Application.OnTime Now() + TimeValue("04:00:00"), "LiveBook"
Application.OnTime Now() + TimeValue("06:00:00"), "LiveBook"
If you want to run it continously every 2 hours without limitation then you need to add
Call SetTimeToRun
to your procedure LiveBook. For Example
Public Sub LiveBook()
Call SetTimeToRun
'your code here …
End Sub
So everytime LiveBook runs it initiates the next run in 2 hours.
But note that the workbook needs to be open all the time in that machine otherwise the timed procedures will not run.
If you need to run a macro at a specific times like 8:30 am, 10:30 am. I recommend to use the windows scheduler to run a VB script or something that opens the workbook, runs the macro and closes the workbook. But note that no one else can use the workbook or the scheduler will fail to open the workbook (only one person can open a workbook at a time for editing).
Also see How to set recurring schedule for xlsm file using Windows Task Scheduler.

Repeat Macro For Specified Time Interval

I have four macros that I want to run every 10 minutes in a specified order. Currently I just set a reminder to run them, but would like to automate the process. Ideally I would love to have a separate macro that repeats all four macros (in order) every 10 mins.
I have tried adding Application.OnTime Now + TimeValue("00:10:00"), "Macro_Name" at the end of the four macros. Issue is two of the macros take some time to process.
Also tried creating a separate Macro "Repeat_10mins", and building it using the OnTime function. Only seems to work once, and doesn't repeat (i.e, runs 10 mins after setting but does not repeat).
Sub Repeat_10mins
Workbooks("Book1.xlsm").RefreshAll
'Repeat Macro1
Application.OnTime Now + TimeValue ("00:10:00"), "Macro1"
'Repeat Macro2
Application.OnTime Now + TimeValue ("00:10:00"), "Macro2"
(etc for Macro 3/4)
End Sub
You will need to create one more macro like this:
Sub Timer()
Application.OnTime Now + TimeValue("00:10:00"), "operation"
End Sub
Where operation is the name of the macro you want to run every 10 minutes.
On the macro you have built you will need to add only one line at the end which is Call Timer.
Explanation:
At the end of the macro operation it will call the macro timer which in 10 minutes will run operation.
Let me know if it works or if you need any more help.

How to refresh database data in Excel at regular intervals?

In an Excel spreadsheet/VBA script I'm making, I need to call data from a database, and refresh the values every 5 minutes. The program starts from the push of a button, and should run continuously until the user breaks the execution. I'm currently not sure how to make Excel/VBA 'wait' 5 minutes without pausing the spreadsheet and, ideally, without being computationally inefficient.
I've tried using the "Application.Wait" and "Sleep" functions, but both of those pause the spreadsheet during the 5 minute wait.
My current solution is to use a "While" loop with "DoEvents" inside it, as shown in the code below. This makes the program just run the "While" loop for 5 minutes, and it does not pause the spreadsheet thanks to "DoEvents". However, while the spreadsheet is usable, this is computationally inefficient, since the program execution isn't technically paused, it's just running the "While" loop continuously, and some of the slower computers that may end up using my program might be significantly slowed by this.
My current solution is as follows:
Sub MainProgram()
'dimension variables, open database connection, etc.
Do While 1 < 2 'ad infinitum
'get database data, write to spreadsheet, etc.
WasteTime()
Loop
End Sub
Sub WasteTime()
EndTime = Now + TimeSerial(0,5,0)
While Now < EndTime
DoEvents
Wend
End Sub
The problem with this, as mentioned above, is the computational inefficiency. CPU utilization is fairly high throughout the WasteTime loop. So I'm wondering, is there any way to pause the script without pausing the spreadsheet and without running the code continuously, thus burdening the CPU?
As BigBen mentions in comments Application.OnTime is the best option for this. It avoids the overhead you describe by scheduling a second macro to be called at a future time.
Below is an example. You can modify the wait time with the constant variable. These should be within the same Module (or change theCalculation macro to not be private).
Sub TheTimerMac()
'enter in timevalue (hour:Minute:Second)
Const DelayTime As String = "00:05:00"
Dim nextRunTime As Date
nextRunTime = Now + TimeValue(DelayTime)
'Schedules application to execute below macro at set time.
Application.OnTime nextRunTime, "TheCalculation"
End Sub
Private Sub TheCalculation()
'whatever you use for your calc here
Application.CalculateFull
'This will restart the timer portion.
Call TheTimerMac
End Sub

Resources