I want to select userforms safely without accidentally loading new instances of the userforms, at the same time I want to avoid too much code. So far I have addressed userforms directly, i.e. with the caption of the userform, e.g.
Userform1.Show
But often I need or want to search and load userforms by name in the VBA.project, because it would simplify some functions for me. But since I use both variants, depending on how the code is executed, a second instant is created. I want to avoid this. I can convert any direct call (Userform1.Show) to Show_Userform("Userform1"), but there are numerous other functions that use Userform1 directly and I would have to convert all of them to objects first to continue abriting.
The real question I have is is there a safe way when calling UserForm1.Show to load the already loaded instance Show_Userform("UserForm1") instead of creating a new one? I read through Difference between declaring a userform as Object vs MSForms.Userform? which was helpful but my problem is not described
Sub Test_Works()
Dim obj As Object
UserForm1.Show (False)
Show_Userform ("UserForm1")
End Sub
Sub Test_Creats_Second_Instance()
Dim obj As Object
'Is there a way to avoid that second instance being created?
Show_Userform ("UserForm1")
UserForm1.Show (False)
End Sub
Sub Show_Userform(sName As String)
Dim obj As Object
'~~> Set userform if still loaded
For Each obj In VBA.UserForms
If StrComp(obj.Name, sName, vbTextCompare) = 0 Then
obj.Show (False)
Exit Sub
End If
Next obj
'~~> Get userform if not loaded yet
On Error Resume Next
Set obj = VBA.UserForms.Add(sName) 'triggers Initialize of the Userform
obj.Show (False)
On Error GoTo 0
End Sub