正确的 VBA 代码关闭工作簿而不保存

Proper VBA code to close workbook without saving

只要在打开多个工作簿的情况下执行代码,office 就会停止工作并显示一条消息

Microsoft Office Excel has stopped working

Windows can try to recover your information and restart the program.

代码有什么问题?我在 Windows7

上使用 MS Office 2007
Private Sub Workbook_BeforeClose(Cancel As Boolean)
    close_without_saving
End Sub

Sub close_without_saving()
    Application.DisplayAlerts = False
    ThisWorkbook.Saved = True

    If Application.Workbooks.Count < 2 Then
        Application.Quit
    Else
        ThisWorkbook.Close
    End If
End Sub

如果您想在不合并更改的情况下关闭工作簿。然后你可以在工作簿模块中使用这样的代码 ~

Sub Auto_Close() 
    ThisWorkbook.Saved = True 
End Sub

您也可以使用它关闭工作簿而不保存更改。

Sub CloseBook2() 
    ActiveWorkbook.Close savechanges:=False 
End Sub

此例程可以附加到关闭 X 按钮。工作簿永远不会部分关闭,它将始终关闭此工作簿中包含的所有工作表。 DisplayAlerts = False 和随后的 True 可以合并到例程中。那不应该造成像

这样的问题
Sub CloseBook() 
    Application.DisplayAlerts = False 
    ActiveWorkbook.Close 
    Application.DisplayAlerts = True 
End Sub