Home » excel » excel – How do I unload a userform without closing everything else?

excel – How do I unload a userform without closing everything else?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have two userforms (frmDatastation1 and frmDatastation2). When the user clicks on cmdbutton on frmDatastation1, the first form becomes hidden (frmDatastation.hide) and the second appears (frmDatastation.show). That works fine. When the user is done with frmDatastation2, I’d like to go back to frmDatastation1 and unload frmdatastation2 (to erase all it’s content to use it again later from frmDatastation1). But when I unload frmDatastation2, everything closes (even frmDatastation1).

Here’s my code in frmDatastation2:

frmDatastation1.TextBox1.Text = ""  'this is to reset my textbox not sure it's needed
Me.Hide 'hiding frmDatastation2
Unload frmDatastation1
frmDatastation1.Show vbModeless ' to be able to continue with the next step
frmDatastation1.TextBox1.SetFocus
Unload frmDatastation2 'when this line is executed, it closes everything (even frmDatastation1)
How to&Answers:

Use objects instead of using the global/default instance.

Sub DoSomething()
    Dim parentForm As frmDatastation1
    Set parentForm = New frmDatastation1
    parentForm.Show vbModal
End Sub

There’s no need to really Unload anything then – the object reference parentForm will die when execution exits DoSomething and the object goes out of scope.

Sub ShowChildForm()
    Dim childForm As frmDatastation2
    Set childForm = New frmDatastation2
    childForm.Show vbModal
End Sub

To make your two objects “talk” to each other, you need to pass object references around. Say the child form needs a reference to the parent, it could have a property like this:

Private parentForm As frmDatastation1

Public Property Get Parent() As frmDatastation1
    Set Parent = parentForm
End Property

Public Property Set Parent(ByVal value As frmDatastation1)
    Set parentForm = value
End Property

And then the parent form could do this:

Sub ShowChildForm()

    Dim childForm As frmDatastation2
    Set childForm = New frmDatastation2
    Set childForm.Parent = Me
    childForm.Show vbModal

    textbox1.Text = childForm.textbox12.Text

End Sub

…While the child form could access its parent form like this:

Sub DoSomething()
    Me.Caption = Parent.textbox1.Text
End Sub

If you want to be able to access the properties of a form that’s closed but not yet unloaded/discarded, don’t close it – just hide it instead (you’ll need to implement the behavior in QueryClose to prevent discarding the object when the user “X-out”‘s of the form).