VBA Macro On Timer 样式以每设定的秒数(即 120 秒)运行代码 [英] VBA Macro On Timer style to run code every set number of seconds, i.e. 120 seconds
问题描述
我需要每 120 秒运行一段代码.我正在寻找一种在 VBA 中执行此操作的简单方法.我知道可以从 Auto_Open
事件中获取计时器值以防止必须使用幻数,但我不太明白如何触发计时器来运行某些东西每 120 秒.
I have a need to run a piece of code every 120 seconds. I am looking for an easy way to do this in VBA. I know that it would be possible to get the timer value from the Auto_Open
event to prevent having to use a magic number, but I can't quite get how to fire off a timer to get something to run every 120 seconds.
如果可以避免的话,我真的不想使用带有睡眠的无限循环.
I don't really want to use an infinite loop with a sleep if I can avoid it.
编辑:
基于提供的答案的交叉发布位于:Excel VBA Application.OnTime.我认为使用它是个坏主意......不管怎样?
Cross-post based on an answer provided is at: Excel VBA Application.OnTime. I think its a bad idea to use this... thoughts either way?
推荐答案
第一次打开工作簿时,执行以下代码:
When the workbook first opens, execute this code:
alertTime = Now + TimeValue("00:02:00")
Application.OnTime alertTime, "EventMacro"
然后在工作簿中添加一个名为EventMacro"的宏来重复它.
Then just have a macro in the workbook called "EventMacro" that will repeat it.
Public Sub EventMacro()
'... Execute your actions here'
alertTime = Now + TimeValue("00:02:00")
Application.OnTime alertTime, "EventMacro"
End Sub
这篇关于VBA Macro On Timer 样式以每设定的秒数(即 120 秒)运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!