Suppose you need to add a standard “Are you sure…” confirmation when the user closes an Access form. It’s easy to add the confirmation message to a button you create, but how do you handle it when the user clicks the form’s standard close button (the “x” in the corner)? Simply adding Cancel = True to the Form_Close() event doesn’t work because the close event can’t be cancelled.
The key is to use the Form’s Unload event, because it can be cancelled.
- Private Sub Form_Unload(ByVal Cancel As Integer)
- If MsgBox("Are your sure", vbYesNo + vbQuestion, "Close Form") = vbNo Then
- Cancel = True
- End If
- End Sub
If you’ve created your own Close button that uses Access’ standard docmd.close method you’ll also need to modify your button’s err handler because cancelling the form’s close method will raise error 2501 “The Close action was cancelled”. Here’s a simple example of how to handle the error.
- Private Sub cmdClose_Click()
- On Error GoTo HandleError
- DoCmd.Close(acForm, Me.Name)
- ExitHere:
- Exit Sub
- HandleError:
- '* Error 2501 will be caused by canceling the form close.
- If Err.Number = 2501 Then
- Resume Next
- Else
- MsgBox("Error: " & Err.Number & " (" & Err.Description & ")", vbOKOnly, "Error")
- GoTo ExitHere
- End If
- End Sub