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
Use pass by reference (ByRef)
A function can return a value of any data type, which includes a class type. The value is actually a reference, or handle to class object.
When called within VBA the function will return a range object, but when called from a worksheet it will return just the value, so set test = Range("A1") is exactly equivalent to test = Range("A1"). Value , where "test" is defined as a Variant, rather than a Range.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With