13.7. Variable Scope and Lifetime

Variables declared within class modules exhibit the same scope and lifetime as those declared within standard modules. For example, Private module-level variables are only available to procedures within the same module, and are destroyed when the class instance is destroyed. Public module-level variables are visible to any code that has access to the class instance. Public variables in a class are an easy way to create properties for the class, but lack the ability to perform validation.

Class variables declared at procedure-level remain accessible only to code within that procedure and are destroyed when the procedure exits; unless of course the variable is declared using the Static keyword. In such a case, the variable is destroyed along with the module-level variables when the object is destroyed.

Although the variables used to hold pointers to objects obey the normal scope and lifetime rules as described previously, they demand special consideration, as you will soon see.

To demonstrate how variable scope and lifetime works, create the following two class modules.

clsClass1

Private obj As clsClass2

Public Property Set Link(objMyObject As clsClass2)
    'Create a link from this object to the other one
    Set obj = objMyObject
    Debug.Print "Creating reference to clsClass2 from clsClass1"
End Property
Private Sub Class_Initialize() Debug.Print "Instantiating clsClass1" End Sub Private Sub Class_Terminate() Debug.Print "Terminating clsClass1 instance" ...

Get Access™ 2007 VBA Programmer's Reference 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.