首页 > 解决方案 > 如何在 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 直到下一次运行才完成.. 那么我怎样才能在下一次之前停止它呢?

标签: excelvba

解决方案


您可以使用调用者和被调用者都可以访问的标志来解决它,如下所示:

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

推荐阅读