vba - 如何创建一个 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 个自动同步进程。我错过了什么吗?
解决方案
我会那样做
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
推荐阅读
- jquery - 如何在“loudev”多选中获取所选项目组名称
- c# - 在 C# 中格式化大型 XML 文件(没有 XDocument)
- javascript - 对齐拆分底座 64 部分
- raspberry-pi3 - Dongle K5150 和 IoT Core 的问题
- python - 如何从列表中的多个项目中拆分路径和文件名
- liferay - eclipse中是否有适用于Liferay 7.2 GA1 CE版的插件SDK
- javascript - 使用比较运算符检查数组的内容,涉及指定的顺序
- java - Okhttp: java.net.UnknownHostException
- java - 无法使用 API 29 android studio 在模拟器中运行应用程序
- mysql - 如何使用mysql、rxjs、angular/electron连接mysql服务器