excel - 如何在 excel 2010 中按时间安排在应用程序之前终止 vba 脚本
问题描述
我有一个在工作簿打开时运行的脚本,我在其中设置了一些时间,如下所示
Private Sub Workbook_Open()
Application.OnTime TimeValue("08:00:00"), "MasterMacro"
Application.OnTime TimeValue("10:30:00"), "MasterMacro"
Application.OnTime TimeValue("13:00:00"), "MasterMacro"
End Sub
有一种情况是脚本 MasterMacro 直到下一次运行才完成.. 那么我怎样才能在下一次之前停止它呢?
解决方案
您可以使用调用者和被调用者都可以访问的标志来解决它,如下所示:
Private IsRunning As Boolean
Private Sub Workbook_Open()
IsRunning = False
Application.OnTime TimeValue("08:00:00"), "MasterMacro"
Application.OnTime TimeValue("10:30:00"), "MasterMacro"
Application.OnTime TimeValue("13:00:00"), "MasterMacro"
End Sub
Sub MasterMacro()
If IsRunning Then
Debug.Print "Is already running. Aborting."
Exit Sub
End If
Debug.Print "Starting Master macro"
IsRunning = True
'Lengthy operation
'goes here
IsRunning = False
End Sub
不同的方法
如果主宏测试是否在其循环内请求终止,它可以中止循环并允许主宏的下一次运行
Private TerminationRequested As Boolean
Private Sub Workbook_Open()
TerminationRequested = False
Application.OnTime TimeValue("08:00:00"), "MasterMacro"
TerminateLongRunningOperation
Application.OnTime TimeValue("10:30:00"), "MasterMacro"
TerminateLongRunningOperation
Application.OnTime TimeValue("13:00:00"), "MasterMacro"
End Sub
Sub TerminateLongRunningOperation()
TerminationRequested = True
Application.Wait Now + TimeValue("0:00:10")
End Sub
Sub MasterMacro()
TerminationRequested = False
For i = 1 To 10000
If TerminationRequested Then Exit Sub
' One of many iterations
' goes here
Next i
End Sub
推荐阅读
- python - Django tinyMC 无法在管理面板中加载
- git - 使用 git 子模块进行可重现的构建(依赖管理)?
- typescript - Map 可以将键作为自定义类型吗?
- mongodb - MongoDB $slice 性能
- wpf - 来自不同窗口的 ShowDialog 中的异常
- scenekit - 在 Scenekit 中,摩擦系数如何在一对材料之间应用
- facebook-graph-api - 我是否需要“公共页面内容”权限才能阅读页面帖子?
- sql - 用一个条件计算分区(/不计算 NULL 值)
- android - Android忽略runOnUiThread中语言文件中的字符串
- codeigniter - Google Recatpcha v2 Invisible 根本不工作说缺少输入响应