How to make a macro which executes periodically in

2020-02-28 06:24发布

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

4条回答
该账号已被封号
2楼-- · 2020-02-28 06:59

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.

查看更多
Viruses.
3楼-- · 2020-02-28 07:01

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

查看更多
在下西门庆
4楼-- · 2020-02-28 07:05

You could consider the Windows Task Scheduler and VBScript.

查看更多
该账号已被封号
5楼-- · 2020-02-28 07:18

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.

查看更多
登录 后发表回答