首页 > 解决方案 > 如何创建一个 Excel 宏来停止另一个宏并重新调用它?

问题描述

我在 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

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

标签: vbaexcel

解决方案


我会那样做

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

推荐阅读