在Excel中创建宏,每2秒执行一次其他宏

时间:2011-03-28 06:51:28

标签: excel vba excel-vba

我有一个名为UpdateMacro的宏,它从我的Excel中更新我的数据库

我想创建一个名为RepeatMacro的宏,它会自动每2秒执行一次UpdateMacro,并且只提供启动和停止按钮来启动和停止执行RepeatMacro

怎么做?

2 个答案:

答案 0 :(得分:2)

Google Application.OnTime

E.g。

Dim dtNextRunTime As Date
dtNextRunTime = Now + TimeSerial(0,0,2)
Application.OnTime dtNextRunTime, "MyProcedure", True

要清除先前设定的程序,您需要保存计划的时间,例如。 dtNextRunTime上面),然后使用:

Application.OnTime dtNextRunTime, "MyProcedure", False

这是一个示例VB模块,其中包含StartSchedule / StopSchedule方法,可以帮助您:

Private m_dtScheduledTime As Date
Private m_lDelaySeconds As Long
Private m_bIsScheduled As Boolean

Private Sub DoWork()

    m_bIsScheduled = False

    ' ... do your work

    ' Reschedule at the same frequency once completed
    StartSchedule m_lDelaySeconds, "DoWork"

End Sub

Public Sub StartSchedule(ByVal DelaySeconds As Long)
    StopSchedule
    m_lDelaySeconds = DelaySeconds
    m_dtScheduledTime = Now + TimeSerial(0, 0, m_lDelaySeconds)
    Application.OnTime m_dtScheduledTime, "DoWork", True
    m_bIsScheduled = True
End Sub

Public Sub StopSchedule()
    If m_bIsScheduled Then
        Application.OnTime m_dtScheduledTime, "DoWork", False
        m_bIsScheduled = False
    End If
End Sub

答案 1 :(得分:0)

假设UpdateMacro运行时间不到两秒,这将每两秒运行一次UpdateMacro

Sub RepeatMacro()
    Dim lastRunTime
    Do
        lastRunTime = Now
        Range("A1") = "Last run: " & Format(lastRunTime, "hh:nn:ss")
        Call UpdateMacro
        DoEvents
        Application.Wait lastRunTime + TimeValue("00:00:02")
    Loop
End Sub

Sub UpdateMacro()
    Debug.Print "running UpdateMacro"
End Sub

编辑要从工作表中启动和停止RepeatMacro,请创建一个开始按钮和一个停止按钮,然后将以下代码放入工作表模块中。另请注意,我在DoEvents上面添加了RepeatMacro

Private Sub StartButton_Click()
    Call RepeatMacro
End Sub

Private Sub StopButton_Click()
    MsgBox "Stopped."
    End
End Sub

现在只说End是不好的做法,但你明白了。