vba - 禁用 "Save when Close"提示时 Excel 拒绝关闭

标签 vba excel save

我有一个 Excel 文件,PlannerTool它在关闭时一直提示保存文件,即使它已在 2 秒前保存。这可能是由于一些不稳定的代码。所以我想当文件在某个时间窗口内保存时我会禁用提示。但是,当我这样做时,Excel 拒绝完全关闭。它将关闭工作簿,但仍会出现灰屏。请参阅下面的屏幕截图。
Grey screen that remains after closing the workbook

我用来拒绝提示的代码取自

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/

相关文章:

excel - 在编译以下代码时,我有一个错误对象变量或未设置 block 变量

excel - 如何根据第二个 PowerPivot 表的行对一个 PowerPivot 表进行求和?

excel - 使用 VBA 使用 IF 在单元格中添加公式时出现问题

vba - 特殊字符。不同国家的替代品

excel - 如何从一列数据中过滤对称词?

c++ - 保存未知数量的 int 和 char 输入

ios - 如何在 Objective C 中解析 M3U8 文件?

python - 如何在python中将信息保存到文件中? (简单的编程)

vba - excel vba关于单元格更改错误

excel - 有没有一种方法可以计算字符串中每个单词的字符数,并返回以逗号分隔的值?