Search code examples
classvbaobjectcreation

What is the "right" way to return a new class object from a VBA function?


I am looking for the proper way to create and return a new class object in VBA.

I am familiar with the following pattern for returning a new Type variable (returned by value):

Public Type Foo
    x as Integer
    y as Integer
End Type

Public Function NewFoo() as Foo
    NewFoo.x = 4
    NewFoo.y = 2
End Function

What would be the equivalent syntax for a new Class object (returned by reference)?

Public Function NewMyClass() As MyClass
    ''// ...?
End Function

Solution

  • If you want to return an Object in VBA you have to set it to the Method name

    Public Function NewMyClass() As MyClass
        Set NewMyClass = CreateObject("Some.MyClass");
    End Function