Part IV: Professional Database Development
998
FIGURE 28.11
The Class_Initialize event procedure runs whenever an object is instantiated from the class module.
Consumer Code
Set objProduct = New Product
objProduct.ProductName = “Beans”
A
Product Class
Private Sub Class_Initialize
End Sub
m_ProductID = -1
m_ProductName = vbNullString
m_SupplierID = -1
m_CategoryID = -1
m_QuantityPerUnit = vbNullString
m_UnitPrice = -1
m_UnitsInStock = -1
m_UnitsOnOrder = -1
m_ReorderLevel = -1
m_Discontinued = False
B
C
D
In this small example, you’ll notice that numeric property variables are set to –1, rather than VBA’s
default of zero for numeric variables. This is because certain logic in the class module uses –1 to
determine when certain states — such as when the user is entering a new product — are in effect.
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 28.12.