5

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
e.James
  • 116,942
  • 41
  • 177
  • 214

1 Answers1

15

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
oberfreak
  • 1,799
  • 13
  • 20
  • 1
    Awesome. Can I then still use `NewMyclass.someVariable = someValue`? – e.James Sep 30 '11 at 19:12
  • 2
    As far as i know you can treat the NewMyclass as a normal variable, therefore you should also be able to call methods an properties – oberfreak Sep 30 '11 at 19:13