仅通过VBAclosures应用程序

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

这是我有的代码

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 

对于退出button:

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

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

谢谢!

只需在button处理程序中设置一个标志并在BeforeClose事件中对其进行testing:

在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 – 而是使用硬引用。 这是一个很好的方法来摧毁一个人的一天的工作价值…

由于Workbook_BeforeClose()在工作簿即将closures(无论是否是您的方法)时被调用,您需要在该方法中使用某种方法来知道它是您的button来调用它。 也许是一个全局variables,或隐藏工作表上给定的单元格中的值?