Open, Close Events -- Event Procedures

Description

To create an event procedure that is run when the Open or Close event occurs, set the OnOpen or OnClose property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_Open (Cancel As Integer)Private Sub Report_Open (Cancel As Integer)Private Sub Form_Close ( )Private Sub Report_Close ( )

The Open event procedure uses the following argument.

Argument

Description

Cancel

The setting determines if the opening of a form or report occurs. Setting Cancel to True (-1) cancels the opening of a form or report.


Remarks

You can’t cancel the Close event.

If you want to refer to controls in an Open event procedure, you must first move the focus to the appropriate control or record using the SetFocus method or the GoToRecord or GoToControl method of the DoCmd object.

If an application has only one form loaded at a time, you can place code for displaying or hiding a toolbar in the Open event procedure for a form. The following example displays the toolbar MyToolbar when the form is opened:


Sub Form_Open(Cancel As Integer)
    DoCmd.ShowToolbar "MyToolbar", acToolbarYesSub

See Also

Open, Close Events — Macros.

Example

This example shows how you can cancel the opening of a form when the user chooses a Cancel button. A message box prompts the user to enter order details. If the user chooses Cancel, the Order Details form isn’t opened.

To try the following example, add the following code to the Declarations section of a form.


Private Sub Form_Open (Cancel As Integer)
    Dim intReturn As Integer
    intReturn = MsgBox("Enter order details now?", vbYesNoCancel)
    Select Case intReturn
        Case vbYes
            DoCmd.OpenForm "Order Details"    ' Open Order Details form.
        Case vbNo
            MsgBox "Remember to enter order details by 5pm."
        Case vbCancel
            Cancel = True                    ' Cancel Open event.
    End SelectSub