1

I have this workbook and I want to make it look like a program. I also want people using it to only be able to quit the application thru a specific command button.

Here is the code I have

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

And for the quit button:

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

My problem is that when the user quit the application thru this button, it triggers the Private Sub Workbook_BeforeClose event and cancel the quitting process. How would you fix this?

Thanks!

2 Answers 2

2

Just set a flag in the button handler and test for it in the BeforeClose event:

In 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

...and in the handler...

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

Note that you should avoid calling ActiveWorkbook.Close - use a hard reference instead. That's a really good way to destroy somebody's day's worth of work...

Sign up to request clarification or add additional context in comments.

2 Comments

Oh hey, what I was typing, but with examples! Nice. :)
Working like a charm! Thank you!
-1

Since Workbook_BeforeClose() is called whenever the workbook is about to close (whether it's your method or not) you'll need some way within that method to know that it was your button that called it. Perhaps a global variable, or a value in a given cell on a hidden sheet?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.