仅通过VBA关闭应用程序

时间:2017-03-03 04:45:56

标签: excel vba exit

我有这个工作簿,我想让它看起来像一个程序。 我也希望使用它的人只能通过特定的命令按钮退出应用程序。

这是我的代码

Private Sub Workbook_BeforeClose(Cancel As Boolean)
Application.OnKey "{ESC}"
Cancel = True
MsgBox "Please use the QUIT button to save and close the database."
End Sub

退出按钮:

Sub SAVE_CLOSE
ActiveWorkbook.Save
If Workbooks.Count < 2 Then
Application.Quit
Else
ActiveWorkbook.Close
End If
End Sub

我的问题是,当用户通过此按钮退出应用程序时,它会触发Private Sub Workbook_BeforeClose事件并取消退出过程。你会如何解决这个问题?

谢谢!

2 个答案:

答案 0 :(得分:2)

只需在按钮处理程序中设置一个标志,然后在BeforeClose事件中对其进行测试:

在ThisWorkbook中......

Public okToClose As Boolean                      '<--module level.

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    If Not okToClose Then
        Application.OnKey "{ESC}"
        Cancel = True
        MsgBox "Please use the QUIT button to save and close the database."
    End If
End Sub

......并且在处理程序中......

Sub SAVE_CLOSE()
    ActiveWorkbook.Save
    ThisWorkbook.okToClose = True
    If Workbooks.Count < 2 Then
        Application.Quit
    Else
        ActiveWorkbook.Close
    End If
End Sub

请注意,您应该避免调用ActiveWorkbook.Close - 请改用硬引用。这是摧毁某人一天工作的一个非常好的方法......

答案 1 :(得分:-1)

由于每当工作簿即将关闭时调用Workbook_BeforeClose()(无论它是否是您的方法),您都需要在该方法中使用某种方法来知道它是您的按钮调用它。也许是全局变量,或隐藏工作表上给定单元格中的值?