Reputation: 161
I have used the method Application.ontime() for scheduling some macros.After closing the workbook, it gets opened again and again. to overcome this problem, I set another event on workbook- BeforeClosed. Now it is showing runtime error 1004:Method 'OnTime' of 'Object'_Application failed.I am not getting why this happening even after reffering the help context from web. Below code is given.
Private Sub Workbook_Open()
starttime = Now + TimeValue("00:02:00")
Application.OnTime EarliestTime:=starttime, Procedure:="startapp", schedule:=True
rtime = TimeValue("14:30:00")
Application.OnTime EarliestTime:=rtime, Procedure:="sendreminder", Schedule:=True
Application.OnTime EarliestTime:=rtime, Procedure:="sendreminder_out",Schedule:=True
Application.OnTime EarliestTime:=rtime, Procedure:="SendReminderFromProxy",Schedule:=True
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
MsgBox "Dear" & " " & Environ("USERNAME") & ", " & "Please do not forget to save before closing."
starttime = Now + TimeValue("00:02:00")
Application.OnTime EarliestTime:=starttime, Procedure:="startapp", Schedule:=False
rtime = TimeValue("14:30:00")
Application.OnTime EarliestTime:=rtime, Procedure:="sendreminder", Schedule:=False
Application.OnTime EarliestTime:=rtime, Procedure:="sendreminder_out", Schedule:=False
Application.OnTime EarliestTime:=rtime, Procedure:="SendReminderFromProxy", Schedule:=False
End Sub
Upvotes: 0
Views: 194
Reputation: 166885
When cancelling an OnTime
, you need to use the exact same argument values you used when creating it (except for the third argument).
That means you can't pass a different time when you cancel it.
Dim starttime '<<< store the time values for later use...
Dim rtime
Private Sub Workbook_Open()
starttime = Now + TimeValue("00:02:00")
Application.OnTime EarliestTime:=starttime, Procedure:="startapp", schedule:=True
rtime = TimeValue("14:30:00")
Application.OnTime EarliestTime:=rtime, Procedure:="sendreminder", Schedule:=True
Application.OnTime EarliestTime:=rtime, Procedure:="sendreminder_out",Schedule:=True
Application.OnTime EarliestTime:=rtime, Procedure:="SendReminderFromProxy",Schedule:=True
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
MsgBox "Dear" & " " & Environ("USERNAME") & ", " & "Please do not forget to save before closing."
'use the global variable here
On Error Resume Next '<< prevent error if no schedule is set
' or if already triggered
Application.OnTime EarliestTime:=starttime, Procedure:="startapp", Schedule:=False
Application.OnTime EarliestTime:=rtime, Procedure:="sendreminder", Schedule:=False
Application.OnTime EarliestTime:=rtime, Procedure:="sendreminder_out", Schedule:=False
Application.OnTime EarliestTime:=rtime, Procedure:="SendReminderFromProxy", Schedule:=False
On Error Goto 0
End Sub
Upvotes: 1