excel - VBA准时取消调度

标签 excel ontime vba

我编写了一个宏,该宏在每个工作日下午 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

最佳答案

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

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)

关于excel - VBA准时取消调度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1674467/

相关文章:

excel - 如何用OnTime刷新选择?错误: Cannot run the macro

sql - OLEDB 连接没有刷新日期

VBA:Str(myString) 与 Str(CDbl(myString)) 的作用相同吗?

vba - 另外溢出

vba - Excel VBA 调试 : Loop not searching through the whole range

用于计算 VBA 中总行数的 Excel 文件

excel - OnTime 时间少于 1 秒而不会变得无响应

excel - 如何使用 Application.OnTime 在每天设定的时间调用宏,而无需关闭工作簿

windows - 如何将此代码从 Visual Basic 转换为 Perl?

vba - Excel VBA : Run-time error (Method 'Value' of object 'Range' failed), 但仅限连续运行