Visual Basic Reference

Unload Event Example

This example demonstrates a simple procedure to close a form while prompting the user with various message boxes. In an actual application, you can add calls to general purpose Sub procedures that emulate the processing of the Exit, Save, and Save As commands on the File menu in Visual Basic. To try this example, paste the code into the Declarations section of a form, and then press F5. Once the form is displayed, press ALT+F4 to close the form.

  Private Sub Form_Unload (Cancel As Integer)
   Dim Msg, Response   ' Declare variables.
   Msg = "Save Data before closing?"
   Response = MsgBox(Msg, vbQuestion + vbYesNoCancel, "Save Dialog")
   Select Case Response
      Case vbCancel   ' Don't allow close.
         Cancel = -1
         Msg = "Command has been canceled."
      Case vbYes
      ' Enter code to save data here.
         Msg = "Data saved."'
      Case vbNo
         Msg = "Data not saved."
   End Select
   MsgBox Msg, vbOKOnly, "Confirm"   ' Display message.
End Sub