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

e.James picture e.James · Sep 30, 2011 · Viewed 12.6k times · Source

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

Answer

oberfreak picture oberfreak · Sep 30, 2011

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