3

我编写了一个宏,该宏在第一次打开工作簿时在每个工作日的下午 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
4

1 回答 1

2

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

输入以下内容以在ThisWorkbook15: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)

于 2009-11-04T16:03:01.120 回答