We help IT Professionals succeed at work.

Class Initialise VBA

sublimation asked
Hi, can I pass parameters to the class Initialise method.


Private Sub Class_Initialize()

End Sub

Can take parameters like this:

Private Sub Class_Initialize(name As String)

End Sub

This the leads me to believe that I can then write code like this:

Dim cPerson as New Person("Peter")

But I do not seem to be able to pass a value to the class initialiser....Since the initialiser takes parameters, can somebody tell me how to pass values to them?  I was hoping to be able to pass them at initialisation.   Thanks.
Watch Question

Expert of the Quarter 2010
Expert of the Year 2010
It is not possible. You need a secondary procedure to set properties in VBA
There is no integrated syntax to create custom builder methods. You can fake it with a regular global function, see below.


Public Function CreatePerson(strName As String) As Person

    Set CreatePerson = New Person
    ' something like:
    CreatePerson.Name = strName
    ' or (depending on what the class requires)
    CreatePerson.Initialise strName

End Function

Open in new window


Okay, so there is no way.....
Cheers guys.
Thanks. Afterthought: the line

Private Sub Class_Initialize(name As String)

doesn't compile. It's because it's itself an implementation of the class mechanism used to fake OO in VB. When an instance is created, the "initialise" event is raised; just before it's zapped from memory, the "terminate" event is raised. They are not constructors, they are really event handlers.