gpt4 book ai didi

excel - VBA准时取消调度

转载 作者:行者123 更新时间:2023-12-02 02:00:54 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com