Chapter 28: Object-Oriented Programming with VBA
997
Learning about Class Events
There are two very important built-in events that accompany every Access class module:
Initialize and Terminate. As you’ll soon see, these two events provide invaluable assistance
in many object-oriented programming projects.
Using class events is one thing that’s completely different from using standard code modules. Not
only do class modules maintain their own data states, but they provide events that offer a great
deal of control over how the data is initialized and cleaned up within the class.
The Class_Initialize event procedure
Very often, the property variables or other resources used by a class need to be initialized, or set to
some beginning state. Other than adding a method to trigger initialization, it might not seem obvi-
ous how to add initialization operations to your classes.
For example, let’s say you create a class module that needs to have a recordset open the entire time
the class is used. Perhaps it’s a class where the data needs to be frequently selected from a database.
Frequently opening and closing connections and recordsets can be an unnecessary drain on perfor-
mance. This is especially true when the selected data set doesn’t change from operation to opera-
tion. It’d be much more efficient to open the recordset one time, leave it open while the class is
being used, and then close it at the conclusion of the session.
That’s where the class’s Initialize event comes in. The Initialize event fires whenever an
object is instantiated from the class module. In the following consumer code example, the Class_
Initialize event procedure runs when the object is set to a new instance of the class:
Dim objProduct As Product
Set objProduct = New Product
Select Class from the object drop-down list in the VBA editor, and then select the Initialize
event from the Events drop-down list. You don’t have to do anything else other than add the code
you want to run when an object is instantiated from your class module. Figure 28.11 shows an
example of a Class_Initialize event procedure in the Product class.
The sequence indicated by the numbers in Figure 28.11 are
l (^) The object is instantiated in (A). Before this statement is completed by the VBA engine, the
Class_Initialize event is invoked.
l (^) Notice that ClassInitialize (B) is a private subroutine. It’s owned by the class, and
executes independently of the consumer code. No arguments are passed to Class
Initialize.
l In C, execution is passed back to the consumer code when Class_Initialize ends.
l (^) Finally, at D, execution recommences in the consumer code at the statement following the
object instantiation.