Initialize Event

Syntax

Private Sub object_Initialize()

Description

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.

Rules at a Glance

  • 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.

Programming Tips and 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 Dim mcolMyCollection As Collection ...

Get VB & VBA in a Nutshell: The Language 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.