How does one execute some VBA code periodically, completely automated?
If you need Excel to run some VBA at a specific time, or repeatedly at set intervals, you can use the Application. OnTime method. A basic call to Ontime requires that you supply a time when you want the code to run, and the name of the macro you want to run.
Go to the VBA Editor (Alt + F11) and double-click the name of the spreadsheet that contains the cell that will change or just right-click the worksheet tab and click View Code. In the window that opens, select Worksheet from the left drop-down menu and Change from the right drop-down menu.
Macro that sets the interval my_macro is the name of the macro that you want to run each interval. TimeValue("00:00:10") is the part of the code that says how long to wait before running the macro; this is the interval. Currently, this is set to run the macro every 10 seconds.
You can't run a Excel VBA Macro without opening the File that contains the macro. If you want you can launch the excel application in hidden mode and then run the macro after opening the file in hidden mode from a VBS file.
You can use Application.OnTime to schedule a macro to be executed periodically. For example create a module with the code below. Call "Enable" to start the timer running.
It is important to stop the timer running when you close your workbook: to do so handle Workbook_BeforeClose and call "Disable"
Option Explicit
Private m_dtNextTime As Date
Private m_dtInterval As Date
Public Sub Enable(Interval As Date)
Disable
m_dtInterval = Interval
StartTimer
End Sub
Private Sub StartTimer()
m_dtNextTime = Now + m_dtInterval
Application.OnTime m_dtNextTime, "MacroName"
End Sub
Public Sub MacroName()
On Error GoTo ErrHandler:
' ... do your stuff here
' Start timer again
StartTimer
Exit Sub
ErrHandler:
' Handle errors, restart timer if desired
End Sub
Public Sub Disable()
On Error Resume Next ' Ignore errors
Dim dtZero As Date
If m_dtNextTime <> dtZero Then
' Stop timer if it is running
Application.OnTime m_dtNextTime, "MacroName", , False
m_dtNextTime = dtZero
End If
m_dtInterval = dtZero
End Sub
Alternatively you can use the Win32 API SetTimer/KillTimer functions in a similar way.
There is an application method that can be used for timing events. If you want this to occur periodically you'll have to 'reload' the timer after each execution, but that should be pretty straightforward.
Sub MyTimer()
Application.Wait Now + TimeValue("00:00:05")
MsgBox ("5 seconds")
End Sub
-Adam
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With