vba 如何使用 Application.OnTime 每天在设定的时间调用宏,而无需关闭工作簿

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17301512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 15:58:46  来源:igfitidea点击:

How to use Application.OnTime to call a macro at a set time everyday, without having to close workbook

excelvbaontime

提问by Shayne K

I have written a macro that uses Application.OnTime that works if I manually execute the macro. I'm trying to automate this process so I don't have to write Application.OnTime in "This Workbook" or (Private Sub Workbook_Open() Most of you do this because you can have windows scheduler open the workbook at a certain time which starts the macros on open. I CANNOT USE SCHEDULER.

我编写了一个使用 Application.OnTime 的宏,如果我手动执行该宏,它就可以工作。我正在尝试自动执行此过程,因此我不必在“此工作簿”或(Private Sub Workbook_Open() 中编写 Application.OnTime 大多数人这样做是因为您可以让 Windows 调度程序在特定时间打开工作簿在打开时启动宏。我无法使用调度程序。

Because I am not able to use windows scheduler I will keep the workbook open and the timer should refresh my data then Call "my Macro" at a certain time everyday.

因为我无法使用 Windows 调度程序,所以我将保持工作簿打开,计时器应该刷新我的数据,然后每天在特定时间调用“我的宏”。

Where do I place this code, and how do I set an auto timer?

我在哪里放置此代码,以及如何设置自动计时器?

回答by Kazimierz Jawor

You could create a kind of recurrence procedure. It could look as follows:

您可以创建一种重复程序。它可能如下所示:

Sub Call_At_3_30()
    'first call appropriate procedure 
    Call myProcedure
    'next, set new calling time
    Application.OnTime TimeValue("3:30:00"), "Call_At_3_30"
End Sub

Somewhere you will keep your main procedure, it this situation:

在某个地方你会保留你的主要程序,在这种情况下:

Sub myProcedure
    'your code here
End Sub

In this situation you need to run first subroutine Call_At_3_30only once. But you need to remember that Excel must be turned on all the time.

在这种情况下,您只需要运行第一个子程序Call_At_3_30一次。但您需要记住,Excel 必须始终处于打开状态。

Optionally, if you want to call your procedure after 24 hours you could change .OnTimeinstruction in this way:

或者,如果您想在 24 小时后调用您的程序,您可以.OnTime通过以下方式更改指令:

Application.OnTime Now + 1, "Call_At_3_30"

Some other modifications are possible, too.

其他一些修改也是可能的。