The Class_Terminate event procedure
The opposite of the Initialize event is the Terminate event. The Terminate event fires whenever an object created from the class is set to Nothing, or goes out of scope. In the following code fragment, the Class_Terminate event procedure runs when the object is set to Nothing:
Set objProduct = Nothing
Use the Terminate event to clean up your class module. For example, if a Database or Recordset object has been opened but hasn't been closed by the class, use the Terminate event to perform these operations.
The Terminate event fires as the statement dismissing the object runs, not after. VBA processes one statement at a time, no matter where the statement takes the execution point. Therefore, when the Set objProduct = Nothing executes, the Class_Terminate event procedure runs before the statement ends. This sequence ensures that the class is cleaned up before execution is returned to the code using the class. This process is illustrated in Figure below.
Just as with the Class_Initialize event procedure, the sequence of Class_Terminate's execution is important:
- In A, the object is set to Nothing, or goes out of scope. Before the statement causing these states executes, control is passed to Class_Terminate.
- Just as you saw with Class_Initialize, notice that Class_Terminate (B) is a private subroutine. It's owned by the class and executes independently of the consumer code. No arguments are passed to Class_Terminate.
- Execution is passed back to the consumer code at C, when Class_Terminate ends.
- In D, execution recommences in the consumer code at the statement following the object's dismissal.
In this tutorial:
- Object-Oriented Programming with VBA
- Introducing Object-Oriented Programming
- Defining objects with class modules
- Adding a class module to a database
- Using the product object
- Creating bulletproof property procedures
- Recognizing the Benefits of Object-Oriented Programming
- Managing a class's interface
- Using Property Procedures
- Exploring property-value persistence
- Modifying the Product Class
- Adding a new property to provide extra information
- Class Events
- The Class_Terminate event procedure
- Adding Events to Class Modules
- Creating custom events
- Trapping custom events
- Exploiting Access class module events