VB6Parse / Library / System Interaction / unload

VB6 Library Reference

Unload Statement

Removes a form or control from memory.

Syntax

Unload object

Parts

Remarks

Examples

Simple Form Unload

Unload Form1

Unload Current Form

Private Sub cmdClose_Click()
    Unload Me
End Sub

Unload Control Array Element

Unload txtDynamic(5)

Unload With Cleanup

Private Sub Form_Unload(Cancel As Integer)
    ' Save data before closing
    SaveSettings
    CloseDatabase
End Sub

Conditional Unload

If UserConfirmed Then
    Unload frmDialog
End If

Common Patterns

Save Data Before Unload

Private Sub Form_Unload(Cancel As Integer)
    If DataModified Then
        Dim response As VbMsgBoxResult
        response = MsgBox("Save changes?", vbYesNoCancel)
        If response = vbYes Then
            SaveData
        ElseIf response = vbCancel Then
            Cancel = True ' Prevent unload
        End If
    End If
End Sub

Unload Multiple Forms

Sub CloseAllForms()
    Dim frm As Form
    For Each frm In Forms
        If frm.Name <> "frmMain" Then
            Unload frm
        End If
    Next frm
End Sub

Unload Dynamically Created Controls

Dim i As Integer
For i = 1 To 10
    Unload lblDynamic(i)
Next i

Best Practices

  1. Use Unload vs Hide: Use Unload when you're done with a form and want to free memory. Use Hide when you want to make a form invisible but may need to show it again soon.
  2. Clean Up Resources: Use the Unload event to close database connections, release objects, and perform other cleanup tasks.
  3. Prevent Accidental Closes: Use the QueryUnload event with Cancel = True to prevent forms from being unloaded when necessary.
  4. Main Form Considerations: Unloading the startup form (main form) terminates the application unless you've specified a Sub Main procedure.
  5. Memory Management: Unloading forms and controls frees memory, which is important in applications that create many forms or controls dynamically.

Important Notes

See Also

References

← Back to System Interaction | View all statements