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 has the following argument.

Argument

Description

Cancel

The setting determines if the opening of the form or report occurs. Setting the Cancel argument to True (–1) cancels the opening of the 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 form or to the appropriate control or record by 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", acToolbarYes
End Sub
See Also

DoCmd object, GoToControl method, GoToRecord method, Open, Close events — macros, SetFocus method.

Example

The following example shows how you can cancel the opening of a form when the user clicks a No button. A message box prompts the user to enter order details. If the user clicks No, the Order Details form isn't opened.

To try the example, add the following event procedure to a form.

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