[英]Application.OnTime & BeforeClose
Just want to ask if why do I keep receiving this error?只想问为什么我一直收到这个错误?
Run-time error '1004': Method 'OnTime' of object'_Application' failed
运行时错误“1004”:对象“_Application”的方法“OnTime”失败
So, I'm trying to close my workbook but whenever I'm doing it, the error shows.所以,我正在尝试关闭我的工作簿,但每当我这样做时,都会显示错误。 The highlighted line after clicking the Debug button is
Application.OnTime timeCheck, "SaveThis", , False
in the Workbook_BeforeClose
sub.单击 Debug 按钮后突出显示的行是
Workbook_BeforeClose
子中的Application.OnTime timeCheck, "SaveThis", , False
。 What seems to be the problem here?这里似乎有什么问题?
Private Sub Workbook_Open() 'place in ThisWorkbook
timeCheck = Now + TimeValue("00:15:00")
Application.OnTime timeCheck, "SaveThis"
End Sub
Sub SaveThis() 'place in Module
timeCheck = Now + TimeValue("00:15:00")
Application.DisplayAlerts = False
ThisWorkbook.Save
Application.DisplayAlerts = True
Application.OnTime timeCheck, "SaveThis"
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean) 'place in ThisWorkbook
Application.OnTime timeCheck, "SaveThis", , False
End Sub
It seems to me that you are trying to schedule a call to SaveThis()
in the future, right when the application is about to close.在我看来,您正试图安排将来调用
SaveThis()
,就在应用程序即将关闭时。 Why would you want to do that?, if the error never happened, then how will you guarantee that the call happens when the workbook is already closed?你为什么要这样做?,如果错误从未发生过,那么你将如何保证在工作簿已经关闭时调用发生?
If what you meant to do is save the workbook before closing the workbook, then you will need to change your code as follows:如果您的意思是在关闭工作簿之前保存工作簿,那么您需要按如下方式更改代码:
Private Sub Workbook_Open() 'place in ThisWorkbook
timeCheck = Now + TimeValue("00:15:00")
Application.OnTime timeCheck, "SaveThis"
End Sub
Sub SaveThis()
timeCheck = Now + TimeValue("00:15:00")
SaveRightNow ' This is a new sub that you will need to add
Application.OnTime timeCheck, "SaveThis"
End Sub
Sub SaveRightNow()
Application.DisplayAlerts = False
ThisWorkbook.Save
Application.DisplayAlerts = True
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean) 'place in ThisWorkbook
SaveRightNow ' Saves the workbook without having to schedule a call in the future
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.