Load, Unload Events — Event Procedures

Description

To create an event procedure that runs when the Load or Unload event occurs, set the OnLoad or OnUnload property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_Load( )

Private Sub Form_Unload(Cancel As Integer)

The Unload event has the following argument.

Argument

Description

Cancel

The setting determines whether to unload the form. Setting Cancel to True (–1) prevents the form from being unloaded.


Remarks

You can place initialization code in a form's Load event procedure. For example, you can specify default settings for controls and initialize form-level variables.

You can't cancel the Load event.

In an Unload event procedure, you can include any form-level validation code you might need to close the form or save the data it contains to a file.

If Cancel is set to True for a form that is modal, you may not be able to return control to the rest of the application.

See Also

Load, Unload events — macros.

Example

The following example displays the current date in the form's caption when the form is loaded.

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

Private Sub Form_Load()
    Me.Caption = Date
End Sub
The next example prompts the user to verify that the form should close.

To try the example, add the following event procedure to a form. In Form view, close the form to display the dialog box, and then click Yes or No.

Private Sub Form_Unload(Cancel As Integer)
    If MsgBox("Close form?", vbYesNo) = vbYes Then
        Exit Sub
    Else
        Cancel = True
    End If
End Sub