Search code examples
excelvbauserform

Passing userform as parameter to form launching utility


I am trying to create a utility which launches a new instance of a specified userform with custom parameters, but I am having trouble passing the desired userform to the utility.

In a module:

Public Sub LaunchForm(MachID As String, FormType As UserForm)

Dim Form As New FormType

With Form
    .MachineID = MachID
    .Show
End With  

End Sub

In the userform from which the form is to be launched:

Private Sub RemovePart32_Click()
   LaunchForm "Machine32", RemovePart
End Sub

When I click the "RemovePart32" button, I get a compile error "user defined type not defined". I am guessing that I should pass the userform as a string but I get a type error if I do that and I'm not sure how to get around that. Any advice would be appreciated.


Solution

  • FormType is actually a variable that you've declared as one of the parameters in LaunchForm, not a type. And so you cannot create a new instance of a variable.

    Since you want to invoke the Show method of the userform passed to LaunchForm, you should pass the userform by value as a generic object.

    Alternatively, you can pass the userform by reference as the actual class of the userform, which would be the name of the userform itself (ie. UserForm1 or whatever else you may have named it).

    So, for example, to pass your userform by value as a generic object, try...

    Public Sub LaunchForm(MachID As String, ByVal Form As Object)
    
        With Form
            .MachineID = MachID
            .Show
        End With
    
    End Sub
    

    Note, when it comes to objects, it's the reference to that object that gets passed to the called procedure. And that reference can be passed ByRef and ByVal.

    When passed ByRef, the reference is passed by reference and the called procedure can change the object to which that reference refers to.

    When passed ByVal, only a copy of the reference is passed.

    For a more detailed explanation, see this article.