Initialize Event |
Private Sub object_Initialize()
Use the Initialize event of an object or class to prepare the object or class for use, setting any references to subobjects or assigning values to module-level variables.
The Initialize event is triggered automatically when an object or class module is first used. The precise point at which the Initialize event is fired depends on how the object is created.
The Initialize event isn't triggered by the declaration of a new object. It's not until the object is used for the first time that the Initialize event is called. For example, in the code fragment:
Dim MyObject As New MyClass 'some code ... 'initialize event called here strName = MyObject.CustName
The assignment of the CustName property value generates the Initialize event, yet in the following code, the Set statement generates the Initialize event.
Dim MyObject As MyClass 'some code ... 'initialize event called here Set MyObject = New MyClass StrName = MyObject.CustName
The Initialize event is only private and doesn't take any arguments.
While it's possible to explicitly call the Initialize event from within the object at any stage after the object has been created, it isn't recommended because the code in the Initialize event should be written to be "run once" code.
Use the Initialize event of a class module to generate references to dependent objects. For example:
Option Explicit Dim mcolMyCollection As Collection Dim moSubObject As mySubObject Private Sub Class_Initialize() Set mcolMyCollection = New Collection Set moSubObject = New mySubObject If glbInstance = 0 Then Set glbMainObj = Me glbInstance = 1 End If End Sub
The Initialize event is triggered only once, when a new object is created. When an object variable is assigned a reference to an existing object, the Initialize event isn't invoked. For example, in the following code fragment, the Initialize event is invoked only once, when the Set objMine1 statement is executed:
Dim objMine1 As MyObj, objMine2 As MyObj Set objMine1 = New MyObj Set objMine2 = objMine1
See Chapter 4 for an in-depth study using classes and objects in VB and VBA.