我的代码现在看起来像这样,剩下要解决的唯一问题是如何在不显示内置对话框的情况下获取“取消”。如果单击是或否,一切正常。但是,当我单击“取消”时,将弹出内置对话框,我必须再次单击“取消”。如何使“取消”像“取消”一样工作,因此不会弹出内置对话框?
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Application.DisplayAlerts = False
If Not closing Then
answer = MsgBox("Save data?", vbYesNoCancel + vbQuestion, "Save data?")
If answer = vbYes Or answer = vbNo Then
closing = True
On Error Resume Next
Application.Visible = False
Application.DisplayFormulaBar = True
ActiveWindow.DisplayHeadings = True
ActiveWindow.DisplayGridlines = True
ThisWorkbook.Unprotect Password:="123456"
ActiveWorkbook.Sheets("Start").Visible = True
ThisWorkbook.Worksheets("Start").Activate
ThisWorkbook.Protect Password:="123456", Structure:=True, Windows:=False
ActiveWorkbook.Close savechanges:=answer = vbYes
Else
Cancel = True
End If
End If
Application.DisplayAlerts = True
End Sub
这是它的外观(我使用Office 2016):
答案 0 :(得分:0)
这是问题所在:ActiveWorkbook.Close savechanges:=answer = vbYes
它再次触发BeforeClose事件。因此,您应该事先禁用事件,然后再重新启用它们。
Application.EnableEvents=False
ActiveWorkbook.Close savechanges:=answer = vbYes
Application.EnableEvents=True