I think that you should keep a reference to the time so that you can cancel the action. You can only cancel an action if it hasn't already executed.
In ThisWorkbook
enter the following to run the macro at 15:59 until the sheet is closed
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
Then add your macro to a Module
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
This way the same value of dTime
will be used to cancel the scheduled task as was used to create it.
If no further task has been scheduled i.e. by an error in MacroTimeTest then the Workbook close event will handle the error.
To see the debug output look at the immediate window in the VBA Editor (Ctrl+G)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…