Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 425
e.James Avatar asked Sep 30 '11 18:09

e.James


People also ask

What is the method for returning more than one values from a function in VBA?

Use pass by reference (ByRef)

Can a function return a class?

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.

What is the return type of function in VBA?

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.


1 Answers

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
like image 193
oberfreak Avatar answered Oct 04 '22 18:10

oberfreak