Search code examples
excelvbauserform

VBA Excel Userforms, Show, Hide


I have a question regarding instances of userforms.

When a userform is constructed via an object in a module (e.g. set frm = new Userform2) can I hide it and restore it by the show method even when the sub is run until the end?

Let's say:

  1. userform creation by sub1
  2. entering values to the userform
  3. hiding the userform with sub2
  4. restore userform with all values by sub3 with the show method

I got really strange behavior when testing code with show and hide methods on module level or Userform Code but what I got finally to work is that using a global variable and the following code in a standard module:

Global frm As UserForm2
Option Explicit

Sub sub1()
Set frm = New UserForm2
    With frm
        .Show vbModeless
    End With
End Sub

Sub sub2()
    With frm
        .Hide
    End With
End Sub

Sub sub3()
    With frm
        .Show vbModeless
    End With
End Sub

It's often said that global variables should be avoided. Is it even possible here? Do I miss something?


Solution

  • What I really want is to hide the userform but keep the instance with all values set before. Here is my original code and I now realized that I mixed things up and made and error. I had an "end" in a condition and this forces the UF not to show resp. killing all instances. @Chronocidal: In fact I hide within code within the UserForm. This is part of a button which transfers set data from UF to sheet. But I think that is not important where to hide or? Now it is working as I expected. Thanks to all of you

    Global myfrm As FormFillInformation
    Option Explicit
    
    Sub InitUserFormGeneralInformation()
    Dim chkfrm As Boolean
    chkfrm = CheckFrmIsHidden
    If chkfrm = True Then
        myfrm.Show vbModeless
        End '<<<<<========== completely wrong but overseen
    Else
        Set myfrm = New FormFillInformation
        myfrm.Show vbModeless
    
    End If
    
    End Sub
    
    
    Function CheckFrmIsHidden() As Boolean
    Dim frm As Object
    CheckFrmIsHidden = False
    For Each frm In VBA.UserForms
     If frm.Name = "FormFillInformation" Then
        CheckFrmIsHidden = True
     End If
    Next
    End Function