VBA Macro On Timer样式每隔几秒钟运行代码,即120秒

问题描述 投票:38回答:6

我需要每120秒运行一段代码。我正在寻找一种在VBA中执行此操作的简单方法。我知道有可能从Auto_Open事件中获取计时器值以防止必须使用幻数,但我无法完全了解如何触发计时器以获得每120秒运行一次的东西。

如果我可以避免它,我真的不想在睡眠中使用无限循环。


编辑:

基于提供的答案的交叉帖子位于:Excel VBA Application.OnTime. I think its a bad idea to use this... thoughts either way?

excel vba excel-vba timer scheduling
6个回答
60
投票

首次打开工作簿时,执行以下代码:

alertTime = Now + TimeValue("00:02:00")
Application.OnTime alertTime, "EventMacro"

然后在工作簿中有一个名为“EventMacro”的宏将重复它。

Public Sub EventMacro()
    '... Execute your actions here'
    alertTime = Now + TimeValue("00:02:00")
    Application.OnTime alertTime, "EventMacro"
End Sub

21
投票

是的,您可以使用Application.OnTime,然后将其放入循环中。它有点像闹钟,你可以在你希望它再次响铃的时候保持按下按钮。以下内容每三秒更新一次Cell A1。

Dim TimerActive As Boolean
Sub StartTimer()
    Start_Timer
End Sub

Private Sub Start_Timer()
    TimerActive = True
    Application.OnTime Now() + TimeValue("00:00:03"), "Timer"
End Sub

Private Sub Stop_Timer()
    TimerActive = False
End Sub

Private Sub Timer()
    If TimerActive Then
        ActiveSheet.Cells(1, 1).Value = Time
        Application.OnTime Now() + TimeValue("00:00:03"), "Timer"
    End If
End Sub

您可以将StartTimer程序放在Auto_Open事件中并更改Timer中的操作(现在它只是用ActiveSheet.Cells(1, 1).Value = Time更新A1中的时间)。

注意:您需要代码(除了StartTimer)在模块中,而不是工作表模块。如果您在工作表模块中有它,代码需要稍作修改。


8
投票

在工作簿事件中:

Private Sub Workbook_Open()
    RunEveryTwoMinutes
End Sub

在一个模块中:

Sub RunEveryTwoMinutes()
    //Add code here for whatever you want to happen
    Application.OnTime Now + TimeValue("00:02:00"), "RunEveryTwoMinutes"
End Sub

如果您只想在工作簿打开后执行第一段代码,那么只需在Workbook_Open事件中添加2分钟的延迟


2
投票

(这是从MS Access帮助文件中解释的。我确信XL有类似的东西。)基本上,TimerInterval是一个表单级属性。设置后,使用子Form_Timer执行您的预期操作。

Sub Form_Load()
    Me.TimerInterval = 1000 '1000 = 1 second
End Sub

Sub Form_Timer()
    'Do Stuff
End Sub

0
投票

我发现使用OnTime会很痛苦,尤其是在以下情况下:

  1. 您正在尝试编码,每次事件触发时,窗口上的焦点都会被中断。
  2. 您打开了多个工作簿,关闭了应该使用计时器的工作簿,并且它会一直触发并重新打开工作簿(如果您忘记正确地杀死事件​​)。

This article by Chip Pearson非常有启发性。我现在更喜欢使用Windows Timer,而不是OnTime


0
投票

我的解决方案

Option Explicit
Public datHora As Date

Function Cronometro(action As Integer) As Integer 
'This return the seconds between two >calls
Cronometro = 0
  If action = 1 Then 'Start
    datHora = Now
  End If
  If action = 2 Then 'Time until that moment
    Cronometro = DateDiff("s", datHora, Now)
  End If
End Function

如何使用?简单...

dummy= Cronometro(1) ' This starts the timer

seconds= Cronometro(2) ' This returns the seconds between the first call and this one
© www.soinside.com 2019 - 2024. All rights reserved.