VBA ontime取消调度

时间:2009-11-04 15:18:10

标签: excel-vba ontime vba excel

我已经编写了一个宏,它在每个工作日的下午15:30运行时首次打开工作簿。 当工作簿关闭时,它会在下次计划运行宏时尝试打开自己。我试图将调度程序设置为false并且出错。代码如下。 有没有人知道为什么这不起作用?

谢谢

Private Sub Workbook_Open()
    Application.OnTime TimeValue("15:30:00"), "MacroTimeTest"
End Sub

public dtime as date

Sub MacroTimeTest()

    dtime = (Format(Application.Evaluate("workday(today(), 1)"), "DD/MM/YY") & " " & TimeValue("15:30:00"))

    'other code has been deleted doesn't affect dtime variable 
End Sub

Private Sub Workbook_BeforeClose(Cancel As Boolean)

    'I have tried replacing false with 0 etc but it didn't make a difference
    Application.OnTime earliesttime:=dtime, procedure:="MacroTimeTest", schedule:=False

End Sub

1 个答案:

答案 0 :(得分:2)

我认为您应该保留对时间的引用,以便您可以取消操作。您只能取消尚未执行的操作。

ThisWorkbook中输入以下内容以在15:59运行宏,直到工作表关闭

Option Explicit

Private Sub Workbook_BeforeClose(Cancel As Boolean)

    On Error GoTo CouldNotCancel

    Application.OnTime dTime, "MacroTimeTest", , False
    Debug.Print "Cancelled task to run at " & dTime

    Debug.Print "Workbook close"

    Exit Sub


CouldNotCancel:
    Debug.Print "No task to cancel"

End Sub 

Private Sub Workbook_Open()
    Debug.Print "Workbook open"

    dTime = TimeValue("15:59:00")

    Debug.Print "Next run time " & dTime
    Application.OnTime dTime, "MacroTimeTest"

End Sub

然后将宏添加到模块

Option Explicit
Public dTime As Date
Public Sub MacroTimeTest()

    'schedule next run
    dTime = TimeValue("15:59:00")

    'schedule next run
    Debug.Print "Scheduling next run at " & dTime

    Application.OnTime dTime, "MacroTimeTest"

    Debug.Print "Running macro"

End Sub

这样,dTime的相同值将用于取消用于创建它的计划任务。

如果没有安排进一步的任务,即MacroTimeTest中的错误,则工作簿关闭事件将处理错误。

要查看调试输出,请查看VBA编辑器中的即时窗口(Ctrl + G)