我有一个Excel文件PlannerTool
,即使关闭了2秒,它仍会在关闭时提示您保存文件。这可能是由于一些易失的代码。因此,我认为当文件在特定时间范围内保存时,我将禁用提示。但是,当我这样做时,Excel拒绝完全关闭。它将关闭工作簿,但将保留灰屏。请参见下面的屏幕截图。
我用来拒绝提示的代码来自
VBA workbooks.Close without being prompted to if the user wants to save?
以下提供的完整代码:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Application.EnableEvents = False
Dim SaveTime As Date
Dim CurrentTime As Date
Dim TimeDifference As Long
SaveTime = ThisWorkbook.BuiltinDocumentProperties("Last Save Time")
CurrentTime = Now
TimeDifference = DateDiff("s", SaveTime, CurrentTime)
'Gets the time difference between closing and saving in seconds
If TimeDifference <= 10 Then 'Saved less than 10 seconds ago so deny prompt
Application.DisplayAlerts = False 'Code gotten from StackOverflow Question
ThisWorkbook.SaveAs Filename:="PlannerTool", FileFormat:=xlOpenXMLWorkbookMacroEnabled, ConflictResolution:=xlLocalSessionChanges
ThisWorkbook.Saved = True 'Tweaked to fit saving format needs
ThisWorkbook.Close SaveChanges:=False
Application.DisplayAlerts = True
End If
Application.EnableEvents = True
End Sub
如果在关闭工作簿时VB编辑器处于打开状态,则该编辑器将保持打开状态并显示RibbonX_Code
模块。包含工作簿PlannerTool
和代码的VBA项目不再显示在项目树中,表明它们确实已关闭。当我打开1个或多个工作簿时没有什么不同,当我关闭PlannerTool
时,这些保持显示在树中。谁能告诉我为什么Excel无法正常关闭?
答案 0 :(得分:2)
我可以在本地复制此行为,看来调用ThisWorkbook.Close
是问题所在。如果打开工作簿,然后使用Excel菜单将其关闭(“文件”->“关闭”),则它的作用与代码相同。在“手动”情况下,Excel会将应用程序保持打开状态,因为您选择不关闭 Excel -仅关闭打开的工作簿。
如果您手动检查是否应关闭Excel,则此方法应能按预期工作。
If TimeDifference <= 10 Then 'Saved less than 10 seconds ago so deny prompt
Application.DisplayAlerts = False 'Code gotten from StackOverflow Question
ThisWorkbook.SaveAs Filename:="PlannerTool", FileFormat:=xlOpenXMLWorkbookMacroEnabled, ConflictResolution:=xlLocalSessionChanges
ThisWorkbook.Saved = True 'Tweaked to fit saving format needs
ThisWorkbook.Close SaveChanges:=False
Application.DisplayAlerts = True
If Application.Workbooks.Count = 0 Then
Application.Quit
End If
End If
我建议这样做,而不是强迫应用程序本身关闭,因为用户可能会在Excel中打开其他文档。