VBA 宏定时器样式每隔设定的秒数(即 120 秒)运行代码
我需要每 120 秒运行一段代码。我正在寻找一种在 VBA 中执行此操作的简单方法。我知道可以从 Auto_Open
事件中获取计时器值,以防止必须使用幻数,但我不太明白如何启动计时器来运行某些东西每 120 秒一次。
如果可以避免的话,我真的不想在睡眠中使用无限循环。
编辑:
根据提供的答案进行交叉发布位于:Excel VBA 应用程序。OnTime。我认为使用这个......想法是个坏主意?
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.
EDIT:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
当工作簿首次打开时,执行以下代码:
然后在工作簿中有一个名为“EventMacro”的宏来重复它。
When the workbook first opens, execute this code:
Then just have a macro in the workbook called "EventMacro" that will repeat it.
是的,您可以使用
Application.OnTime
来实现此目的,然后将其放入循环中。这有点像闹钟,当你想让它再次响起时,你可以不断地按下贪睡按钮。以下内容每三秒更新一次单元格 A1 的时间。您可以将
StartTimer
过程放入Auto_Open
事件中,并更改Timer
过程中执行的操作(现在它只是更新中的时间) A1 与ActiveSheet.Cells(1, 1).Value = Time
)。注意:您需要将代码(
StartTimer
除外)放在模块中,而不是工作表模块中。如果您将其放在工作表模块中,则代码需要稍作修改。Yes, you can use
Application.OnTime
for this and then put it in a loop. It's sort of like an alarm clock where you keep hittig the snooze button for when you want it to ring again. The following updates Cell A1 every three seconds with the time.You can put the
StartTimer
procedure in yourAuto_Open
event and change what is done in theTimer
proceedure (right now it is just updating the time in A1 withActiveSheet.Cells(1, 1).Value = Time
).Note: you'll want the code (besides
StartTimer
) in a module, not a worksheet module. If you have it in a worksheet module, the code requires slight modification.在工作簿事件中:
在模块中:
如果您只想在工作簿打开后执行第一段代码,则只需在
Workbook_Open
事件中添加 2 分钟的延迟In Workbook events:
In a module:
If you only want the first piece of code to execute after the workbook opens then just add a delay of 2 minutes into the
Workbook_Open
event(这是从 MS Access 帮助文件中转述的。我确信 XL 也有类似的东西。) 基本上,TimerInterval 是一个表单级属性。设置后,使用子 Form_Timer 执行您想要的操作。
(This is paraphrased from the MS Access help files. I'm sure XL has something similar.) Basically, TimerInterval is a form-level property. Once set, use the sub Form_Timer to carry out your intended action.
我发现使用
OnTime
可能会很痛苦,特别是在以下情况下:每次事件触发时。
Chip Pearson 的这篇文章非常具有启发性。我现在更喜欢使用 Windows 计时器,而不是
OnTime
。I've found that using
OnTime
can be painful, particularly when:every time the event triggers.
This article by Chip Pearson was very illuminating. I prefer to use the Windows Timer now, instead of
OnTime
.我的解决方案:
如何使用?简单的...
My solution:
How to use? Easy...