To create an event procedure that is executed when the Load or Unload event occurs, set the OnLoad or OnUnload property to [Event Procedure], and click the Build button.
Private Sub Form_Load( )Private Sub Form_Unload(Cancel As Integer)
The Unload event uses the following argument.
Argument |
Description |
Cancel |
The setting determining whether to unload the form. Setting Cancel to True (-1) prevents the form from being unloaded. |
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.
Load, Unload Events — Macros.
The following example displays the current date in the form’s caption when the form is loaded.
Private Sub Form_Load() Me.Caption = DateSub
The next example prompts the user to verify that the form should close.
To try this example, add the following code to the Declarations section of a module for a form. In Form view, close the form to display the dialog box, and then choose Yes or No.
Private Sub Form_Unload(Cancel As Integer) If MsgBox("Close form?", vbYesNo) = vbYes Then Exit Sub Else Cancel = True End IfSub