使用 VBA 禁用关闭 (X) 并需要一个按钮来关闭和保存

Use VBA to disable Close (X) and Require a Button to Close and Save

Private Sub Workbook_BeforeClose(Cancel As Boolean)
If wrkBkClose = False Then
MsgBox ("Please Use The Save & Close Button"), vbInformation
Cancel = Not wrkBkClose
End If
End Sub

工作簿关闭前事件

Sub CloseSave()
Application.EnableEvents = False
Application.DisplayAlerts = False

If Application.Workbooks.Count = 1 Then
    wrkBkClose = True
    ActiveWorkbook.Close SaveChanges:=True
    Application.Quit
Else
    With ActiveWorkbook
        .Close SaveChanges:=True
    End With
End If

End Sub

按钮下的模块

以上代码按预期工作,除了 Excel 应用程序没有完全关闭。以下内容仍未完成:

谁能帮我理解为什么应用程序不能完全关闭?或者有没有其他方法我应该去执行这个程序。在此先感谢您的帮助。

仅通过按钮关闭工作簿

  • 如果它是唯一打开的工作簿,它也会退出Excel。

本工作簿

Option Explicit

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    If wrkBkClose = False Then
        MsgBox ("Please Use The Save & Close Button"), vbExclamation
        Cancel = True
    End If
End Sub

模块 1

Option Explicit

Public wrkBkClose As Boolean

Sub CloseSave()
    wrkBkClose = True
    If Application.Workbooks.Count = 1 Then
        ThisWorkbook.Save
        Application.Quit
    Else
        ThisWorkbook.Close SaveChanges:=True
    End If
End Sub