Developer

VB6 Tip: Best practices requires that you ensure all forms unload

Writing proper code requires that when a VB program ends, all of its forms will be unloaded and removed from memory.

When a Visual Basic 6 program ends, all of its forms should be unloaded and removed from memory. VB doesn't do this automatically; therefore, if your program contains a lot of forms, it's possible for one or more forms to remain in memory even after the program terminates.

Calling a form's Hide method or setting its Visible property to False doesn't unload it. Even if you explicitly unload a form (using the Unload procedure), it can still take up resources—unless the form's reference is set to Nothing. This tip shows how to ensure that all of the forms in a program unload and that their resources release upon program termination.

This technique makes use of the fact that a VB application has a global Forms collection whose elements represent all of the application's loaded forms.

You could loop through this collection, unloading all forms as shown in this code snippet:

Dim f As Form
For Each f In Forms
  Unload f
  Set f = Nothing
Next f

There's a problem with this straightforward approach: If you execute this code from a procedure, it works fine; but if you call it from the main form's Form_Unload event procedure, it will try to unload the main form, which is already in the process of unloading itself (otherwise the Form_Unload event procedure wouldn't have fired). Here's how you can get around this potential problem:

Public Sub UnloadAllForms(Optional FormToIgnore _
  As String = "")

  Dim f As Form
  For Each f In Forms
    If f.Name <> FormToIgnore Then
      Unload f
      Set f = Nothing
    End If
  Next f
   
End Sub

With this procedure in place, you'd call it like this from the main form's Form_Unload event procedure:

UnloadAllFormsMe.Name

It will unload all forms except the main form.

If calling it from a separate procedure, don't pass an argument, and the procedure will unload all of the program's forms.

Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!

Editor's Picks