Question

How does one execute some VBA code periodically, completely automated?

Was it helpful?

Solution

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.

OTHER TIPS

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

You could consider the Windows Task Scheduler and VBScript.

I do this all the time, I used to use the "OnTime" method as shown above but it renders the machine you are running the code on useless for other things, because Excel is running 100% of the time. Instead I use a modified hidden workbook and I execute with windows Task Scheduler and in the thisworkbook workbook_open function call the macro from your personal workbook, or open and run another workbook with the code in it. After the code has run you can call the application.quit function from the hidden workbook and close ecxel for the next run through. I use that for all my on 15 minute and daily unattended reporting functions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top