我有一个 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 不能正常关闭?
最佳答案
我可以在本地复制此行为,并且似乎调用 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 中打开了其他文档。
关于vba - 禁用 "Save when Close"提示时 Excel 拒绝关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51672204/