tags:

views:

1704

answers:

5

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

+1  A: 

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 Davis
+7  A: 

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
    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.

Joe
... to fully automate this fine answer, addCall MacroName()to the Workbook_Open() event.This way, whenever you open the xls/xlsm, the MacroName starts its traits without any user intervention.
jpinto3912
A: 

You could consider the Windows Task Scheduler and VBScript.

Remou
A: 

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.

CABecker
I have to say this is not true anymore. I'm running a Sub periodically right now (once every second) and excel does not hog CPU at all.
rix0rrr
A: 

Hello there

when i try to use that code, i get an error: "The macro 'I:\myFolder\test.xls'!MacroName was not found"

when i try to call MacroName not through the OnTime method, it works fine. i have excel 2003 why does this happen?

thanks in advance