如何创建一个Excel宏来停止另一个宏并重新调用它?

时间:2018-10-02 04:06:14

标签: excel vba excel-vba

我在Excel文件中有一个宏,该宏可以连续运行30秒的计时器:

Sub autosync()

  Call syncSQL 'a sync function that copies data rows to database.
  Application.OnTime Now + TimeValue("00:00.30"), "Sheet7.autosync"

End Sub

但是,有时会发生错误使计时器停止运行,因此我想创建一个按钮,该按钮不仅可以恢复计时器,还可以终止旧计时器并将其替换为新计时器。这是为了避免多个计时器同时运行。

Sub resetsync()

Application.OnTime Now + TimeValue("00:00:30"), "Sheet7.autosync", False    '1. Stops the current timer
Call autosync  '2. Call back the timer

End Sub

但是,当我测试按钮时,它会忽略第1步,直接进入第2步,创建2个自动同步过程。我想念什么吗?

2 个答案:

答案 0 :(得分:1)

我会那样做

Option Explicit

Dim iTimerSet As Double

Public Sub StopTimer()

 On Error Resume Next ' Lazy programming
 Application.OnTime iTimerSet, "RunTimer", , False

End Sub

Public Sub RunTimer()

    ' Some Demo Code
    ' here you can put your code
    ' Call syncSQL
    MsgBox "Call syncSQL ", vbOKOnly, "Test"


    ' Code to start the timer
    ' example every 5 seconde
    iTimerSet = Now + TimeValue("00:00:05")
    Application.OnTime iTimerSet, "RunTimer"

End Sub

答案 1 :(得分:0)

无论何时启动计时器,都需要将计划的时间存储在Gobal / Static变量中:这是您要取消该计时器时需要使用的值。

参见例如:Bettersolutions.com/vba/macros/application-ontime.htm

Dim exTime
Sub autosync()

  Call syncSQL 'a sync function that copies data rows to database.
  exTime = Now + TimeSerial(0, 0, 30)
  Application.OnTime exTime, "Sheet7.autosync"

End Sub


Sub resetsync()
    'EDIT - needs the "Schedule" parameter name...
    Application.OnTime exTime, "Sheet7.autosync", Schedule:=False '1. Stops the current timer
    Call autosync  '2. Call back the timer

End Sub