2017-03-03 91 views
1

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

这里是我的代码有

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 

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

谢谢!

回答

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 - 请改为使用硬引用。这是一个很好的方式来摧毁某人的一天的工作......

+0

哦,嘿,我正在打字,但有例子!尼斯。 :) – steegness

+0

工作就像一个魅力!谢谢! – Alex

-1

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