2017-03-03 92 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()在工作簿即將關閉時(無論是否是您的方法)被調用,您需要在該方法內使用某種方法知道這是你的按鈕,它叫。也許是全局變量,或隱藏工作表上給定單元格中的值?