Introduction
When closing a UserForm in VBA, there are two similar methods: the Unload statement and the .Hide method.
While both result in the form disappearing from the screen, there is a distinct difference in how they handle memory and the state of the form. Using them without understanding this difference can lead to unexpected behaviors, such as “values entered in the form disappearing” or “old values remaining when they shouldn’t.”
This article explains the meaning of Unload and .Hide and how to distinguish their usage.
Unload: Completely Terminating the Form
Unload is a command to completely destroy (release) the UserForm from memory.
Characteristics
- The form instance is completely terminated.
- Values entered into TextBoxes or ComboBoxes on the form are all reset to their initial state.
- When the form is displayed again, it appears as a completely new instance.
When to Use
This is suitable when the work on the form is finished and there is no need to retain the input contents. It is generally used for “OK”, “Cancel”, or “Close” buttons to finalize the process.
Sample Code
' --- Assuming a UserForm named MainForm ---
' Processing when the "Close" button (CloseButton) is clicked
Private Sub CloseButton_Click()
' Completely unload the form from memory
Unload MainForm
' Or simply: Unload Me
End Sub
.Hide: Temporarily Hiding the Form
.Hide merely makes the UserForm invisible on the screen, but it continues to exist in memory.
Characteristics
- The form remains in memory, simply becoming invisible.
- Values entered into TextBoxes, etc., are retained as is.
- When displayed again using the
.Showmethod, it appears in the same state as before.
When to Use
This is suitable when you want to temporarily operate on an Excel sheet during input on the form, or when moving back and forth between screens in a multi-step wizard.
Sample Code
' --- Assuming a UserForm named MainForm ---
' Processing when the "Hide Temporarily" button (HideButton) is clicked
Private Sub HideButton_Click()
' Only hide the form (values are retained)
MainForm.Hide
' Or simply: Me.Hide
End Sub
' Macro to redisplay the form (Written in a Standard Module)
Sub ReShowForm()
' Redisplay the hidden form
' The previous input values will still be there
MainForm.Show
End Sub
Summary of Differences: Unload vs. Hide
| Item | Unload | .Hide |
| Purpose | Terminate completely | Hide temporarily |
| Memory | Released (Freed) | Retained (Kept) |
| Input Data | Destroyed (Reset) | Retained |
| Main Use | OK, Close, Cancel | Sheet operations, multi-page navigation |
Conclusion
- Unload: Resets everything and terminates completely.
- .Hide: Temporarily hides while maintaining the state.
Basically, use Unload when the form’s role is finished. Unless there is a specific intention to keep data, avoiding .Hide is safer for memory management and preventing unintended data retention.
