Search code examples
excelvbauserform

VBA: how to pass a form as a paramter


I have a simple user form with a button on it. I want to pass this form to a function in another module - but even inside the same module, it does not work as expected:

Private Sub Test(ByRef oForm As MSForms.UserForm)
    Debug.Print "caption: >" & oForm.Caption & "<"
End Sub

Private Sub CommandButton3_Click()
    Debug.Print "caption: >" & Me.Caption & "<"
    Test Me
    Debug.Print "caption: >" & Me.Caption & "<"
End Sub

when I click the button it prints this to the debug console:

caption: >UserForm1<
caption: ><
caption: >UserForm1<

so inside of the Test() sub the Caption is blank.

any ideas why this does not work?

Note: if I use Variant as parameter-type it works


Solution

  • Type UserForm is not directly equivalent to an instance of a specific User Form and presents a slightly different interface.

    Pass the form as Object:

    Private Sub Test(Form As Object)
    

    or for a type safe approach a UserForm may implement an Interface:

    Private Sub Test(Form As IMyForm)