Code to run macro on time interval?

寵の児 提交于 2019-12-05 20:21:00
Soulfire

Lumigraphics raises a good point about memory usage, which should be considered. In the interest of learning I will present an alternate solution that doesn't require task scheduler and will work completely within the display workbook.

In the VB Editor, add this new subroutine

Public Sub RefreshDataEachHour()

    Application.OnTime Now + TimeValue("01:00:00"), "Refresh_All"

End Sub

And add the following line to the end of your Refresh_All routine

Call RefreshDataEachHour

When the Refresh_All routine is run for the first time it will call this new procedure, which will then wait an hour and then call Refresh_All. Again at the end of Refresh_All it returns to this stored procedure, which will wait an hour again, then call Refresh_All, etc. This will repeat until the Excel application is exited.

This part below is beyond the scope of your question, but I feel it important to mention anyways.

Basically, Application.OnTime schedules a task to run at some point in the future. You may want to end this scheduled task at some point in time. To do so you must call the Application.OnTime method with an argument Schedule:=False and you must pass in the exact time that you scheduled the procedure with your first Application.OnTime call.

To handle this case, declare a global variable (outside of all of your subroutines) and pass that variable into a new subroutine that will cancel the task.

For example, you can declare

Public RunWhen As Date

Then you would modify the above procedure as follows:

Public Sub RefreshDataEachHour()

    RunWhen = Now + TimeValue("01:00:00")
    Application.OnTime EarliestTime:=RunWhen,Procedure:="Refresh_All",Schedule:=True

End Sub

Then you can add another subroutine that would handle the canceling of the task, like so:

Public Sub CancelRefresh()

    Application.OnTime EarliestTime:=RunWhen, Procedure:="Refresh_All", Schedule:=False

End Sub

Whenever you use Call CancelRefresh that should remove your procedure from the queue.

Windows has a built-in Task Scheduler. Put your macro into a workbook and set it to run on the WorkBook.Open event. https://msdn.microsoft.com/en-us/library/office/ff196215.aspx

Set the Task Scheduler to open that Excel file every hour, run the macro, and have it close the file at the end. This cuts down on memory usage vs keeping Excel running. Task Scheduler also has the ability (for example) to send an email, so you could set it to email you when the task ran each hour.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!