Name
Initialize Event
Syntax
Private Sub object
_Initialize( )
Description
Use the Initialize event of a class defined with the
Class...End Class
construct to prepare the object
or class for use, setting any references to subobjects or assigning
default values to properties and values to class-level variables.
Rules at a Glance
The Initialize event is triggered automatically when a class is first instantiated by the
Set
statement. For example, in the following code, theSet
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.
Programming Tips & Gotchas
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 Class CMyClass Private moSubObject Private Sub Class_Initialize( ) Set moSubObject = New mySubObject If glbInstance = 0 Then Set glbMainObj = Me glbInstance = 1 End If End Sub End Class
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 ...
Get VBScript in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.