Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

KISS way to force users to click a command button to exit a form regardless of menu or toolbar options

How to

KISS way to force users to click a command button to exit a form regardless of menu or toolbar options

by  SBendBuckeye  Posted    (Edited  )
I wish I could take credit for thinking of a simple solution like this, but I can't since I came across this in my reading (Access Developers Handbook, Volume 1). I noticed a couple threads on the forums regarding user's closing down forms by exiting Access via the menu or tool bars, etc. so I thought I would write a quick FAQ for it.

Comments, suggestions, feedback, etc. gladly accepted.

Way to only allow form exit if a command button is clicked:

1. Declare a public form module variable such as:
Public AllowClose As Boolean

2. In the On Load or On Open event on your form, add this:
AllowClose = False

3. In the Click event on the Exit command button, add this:
AllowClose = True
DoCmd.Close

4. In the On Unload event on your form, add this:
Cancel = Not AllowClose

5. Test and enjoy

The reason this works is because the Unload event (as opposed to the On Close event) passes a Cancel parameter. If cancel is set to true (which it will be unless your command click event sets AllowClose to true), then the form cannot be unloaded no matter what keys are pressed or buttons are clicked on the form or elsewhere on a menu or toolbar.

This why you don't have to worry about disabling close or exit actions anywhere outside the form because it just doesn't matter. If AllowClose = False then Cancel will be true and the form will NOT unload.

Events that pass the cancel parameter come in handy. Other examples of form controls that pass a cancel parameter include Before Update and On Exit. If you set cancel to true, the control cannot lose focus no matter what the user did. If you want to restore the original value, put controlname.undo somewhere in the validation code before you cancel.

Have a great night all, it's been a long day!

Sample code for the above:

Code:
Option Compare Database
Option Explicit

Public AllowClose As Boolean

Private Sub Form_Load()
    AllowClose = False
End Sub

Private Sub Form_Unload(Cancel As Integer)
    Cancel = Not AllowClose
End Sub
Private Sub cmdClose_Click()
On Error GoTo Err_cmdClose_Click

    AllowClose = True
    DoCmd.Close

Exit_cmdClose_Click:
    Exit Sub

Err_cmdClose_Click:
    MsgBox Err.Description
    Resume Exit_cmdClose_Click
    
End Sub
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top