Advanced: Requires expert coding, interoperability, and multiuser skills.
This article applies to a Microsoft Access database (.mdb) and to a Microsoft Access project (.adp).
MORE INFORMATION
Class modules have the following characteristics:
- The Initialize event
- Your custom functionality
- The Terminate event
Every class module has a lifetime, which is defined as the length of time
that the class continues to be referenced in your code.
The Initialize Event
The Initialize event occurs when an instance of your class is created.
This is the event that you want to use to set up your defaults and
initialize variables, for example.
Your Custom Functionality
You create Private variables, properties, and methods (functions) for
internal use in your class, and Public variables, properties, and methods
that you want to expose to the user implementing your class.
The Terminate Event
The Terminate event occurs when an instance of your class is unloaded
explicitly, or when a reference to the class falls out of scope.
Example of a Procedure That Uses a Class Module
Consider the following sample procedure that references a class module
named clsTest:
Function CreateClass1() As Boolean
Dim cls As New clsTest
Dim varResult As Variant
MsgBox cls.ClassState, vbInformation, "Class Example"
varResult = cls.AddInvoice("ALFKI")
MsgBox cls.ClassState, vbInformation, "Class Example"
Set cls = Nothing
CreateClass1 = True
End Function
This example:
- Creates a new instance of the clsTest Class object.
- Calls the AddInvoice method of the Class object and passes a valid Customer ID.
- Unloads the Class object by setting the cls object equal to Nothing.
The details of what this code accomplishes are not apparent from the sample code. For example, you cannot determine what happens when the
Class
object is created, what the
AddInvoice method does, or what happens when you close the class. That is the point of the class module programming
technique; you can hide the complexity of what occurs behind the scenes in
calls to the
Class object. There are many benefits to class-oriented
programming, which are revealed throughout this article.
Creating a Sample Class Module and Supporting Code
CAUTION: If you follow the steps in this example, you modify the sample database Northwind.mdb. You may want to back up the Northwind.mdb file and follow these steps on a copy of the database.
Each time you create a
Class object, a trappable Initialize event occurs in the class, which is similar to the Open event of a form. The Initialize event is where you program the things that you want your class to do. For C++ programmers, this is similar to a
Constructor.
Follow these steps to create the clsTest class module example:
- Open the sample database Northwind.mdb.
- On the Insert menu, click Class Module.
- Save the class module as clsTest.
- Type the following lines in the Declarations section:
Private This_ClassState As String
Private This_frm As Form
- Select Class in the Object box of the module window. Initialize is automatically selected in the Procedure box.
- Add the following procedure:
Private Sub Class_Initialize()
This_ClassState = "Initialized"
End Sub
- Add the following custom property function:
Public Property Get ClassState() As String
ClassState = This_ClassState
End Property
The code in the Initialize event of clsTest sets the default value for a
read-only property named ClassState. ClassState returns the current status of the
Class object to the caller. It has no functional purpose, but it illustrates techniques you can use when you implement a class module.
The following procedure demonstrates how to retrieve the ClassState
property from the
Class object:
Function GetClass1State() As String
Dim cls As New clsTest
Dim varResult as String
varResult = cls.ClassState
Set cls = Nothing
GetClass1State = varResult
End Function
This procedure returns "Initialized" from the
Class object, which
illustrates the concept that you use when you plan the resulting functionality of your class. You define what you want the class to do, and, additionally, you consider how to implement the interface to your class. This is the same concept as laying out a form so it is aesthetically pleasing to a user, but in this case your target audience is someone who is programming with Visual Basic for Applications.
Create a procedure to use as the AddInvoice method of the clsTest class
module. The code is similar to that in a standard module:
- Create the following procedure in the clsTest class module:
Function AddInvoice(custID As String) As Boolean
On Local Error GoTo AddInvoice_Err
Dim Msg As String
Dim lngOrderID As Long
Dim varResult As Variant
Set This_frm = Form_Orders
This_frm.Modal = True
This_frm.Visible = True
DoCmd.GoToRecord acForm, This_frm.Name, acNewRec
This_frm.CustomerID = custID
varResult = This_frm.SetShipTo
This_ClassState = "RecordActive=" & CStr(This_frm.OrderID)
AddInvoice = True
AddInvoice_End:
Exit Function
AddInvoice_Err:
Msg = "Error #: " & Format$(Err.Number) & vbCrLf
Msg = Msg & Err.Description
Err.Raise vbObjectError, "clsTest.AddInvoice", Msg
Resume AddInvoice_End
End Function
This procedure uses simple programming techniques to open the Orders form, add a new record, and display the record for edits. There are many enhancements you can make to this code using Data Access Objects (DAO). For example, you can modify the code to retrieve the customer's last order and duplicate it without ever opening the Orders form. For illustrative purposes, this example uses the form itself to add a new record.
Note that the error handling event uses the Raise method of the Err object. This action allows the caller of the class, instead of the user, to handle any errors.
- Save and close the clsTest class module.
- Open the Orders form in Design view.
- On the View menu, click Code, and then type the following procedure:
Public Function SetShipTo() As Boolean
Call CustomerID_AfterUpdate
SetShipTo = True
End Function
This procedure in the class module of the Orders form is required to support the clsTest class module example. The procedure calls the AfterUpdate event of the CustomerID control. This is necessary to update the Ship To information on the form, which is triggered through the user interface when a user selects a Customer from the CustomerID list. Because the CreateClass1() sample procedure sets the value of CustomerID in code, this provides a way to trigger the AfterUpdate event and update the Ship To information.
- Close and save the Orders form.
The class module also supports a Terminate event. This event triggers when
a
Class object falls out of scope, or when it is unloaded from memory by
setting its object variable equal to Nothing. The Terminate event is very
important because you use it to clean up any objects or references that the
class itself initiated. For C++ programmers, this is similar to a
Destructor.
Follow these steps to create a Terminate event in the clsTest class module
that closes the Orders form and unloads the This_frm object variable:
- Open the clsTest class module in Design view.
- Select Class in the Object box of the module window.
- Select Terminate in the Procedure box of the module window.
- Add the following procedure:
Private Sub Class_Terminate()
DoCmd.Close acForm, This_frm.Name
Set This_frm = Nothing
MsgBox "Class Terminated", vbInformation, "Class Example"
End Sub
Testing the Sample Class Module
Follow these steps to test the functionality of the clsTest class module:
- Create a new standard module and save it as Module1.
- Type the following procedure:
Function CreateClass1() As Boolean
Dim cls As New clsTest
Dim varResult As Variant
MsgBox cls.ClassState, vbInformation, "Class Example"
varResult = cls.AddInvoice("ALFKI")
MsgBox cls.ClassState, vbInformation, "Class Example"
Set cls = Nothing
CreateClass1 = True
End Function
- To test this function, type the following line in the Immediate window, and then press ENTER.
Note that the function does the following:
- Displays a message box indicating that the class has been
Initialized.
- Opens the Orders form and displays a blank invoice for CustomerID
ALFKI.
- Displays a message box indicating that the RecordActive=OrderId, where OrderID is the number automatically assigned to the new order.
- Closes the Orders form.
- Displays a message box indicating that the class has been Terminated.