ACC2000: Introduction to Stand-Alone Class Module Programming

This article was previously published under Q209968
This article has been archived. It is offered "as is" and will no longer be updated.
Advanced: Requires expert coding, interoperability, and multiuser skills.

This article applies to a Microsoft Access database (.mdb) and to a Microsoft Access project (.adp).

This article describes how to conceptualize and implement stand-alone classmodules in Microsoft Access 2000. Class modules were introduced in Microsoft Access 7.0, where class modules behind forms and reports allowyou to create procedures that define custom methods and properties for theobject.

Access 2000 supports stand-alone class modules that allow you to create an instance of a class that presents no user interface unless you program it to do so.
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 timethat 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 andinitialize variables, for example.

Your Custom Functionality

You create Private variables, properties, and methods (functions) forinternal use in your class, and Public variables, properties, and methodsthat you want to expose to the user implementing your class.

The Terminate Event

The Terminate event occurs when an instance of your class is unloadedexplicitly, 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 modulenamed 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 = TrueEnd 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 Classobject is created, what the AddInvoice method does, or what happens when you close the class. That is the point of the class module programmingtechnique; you can hide the complexity of what occurs behind the scenes incalls to the Class object. There are many benefits to class-orientedprogramming, 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:

  1. Open the sample database Northwind.mdb.
  2. On the Insert menu, click Class Module.
  3. Save the class module as clsTest.
  4. Type the following lines in the Declarations section:
    Private This_ClassState As StringPrivate This_frm As Form					
  5. Select Class in the Object box of the module window. Initialize is automatically selected in the Procedure box.
  6. Add the following procedure:
    Private Sub Class_Initialize()   This_ClassState = "Initialized"End Sub					
  7. Add the following custom property function:
    Public Property Get ClassState() As String   ClassState = This_ClassStateEnd Property					
The code in the Initialize event of clsTest sets the default value for aread-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 ClassStateproperty from the Class object:
Function GetClass1State() As String   Dim cls As New clsTest   Dim varResult as String   varResult = cls.ClassState   Set cls = Nothing   GetClass1State = varResultEnd Function				
This procedure returns "Initialized" from the Class object, whichillustrates 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 classmodule. The code is similar to that in a standard module:
  1. 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 = TrueAddInvoice_End:   Exit FunctionAddInvoice_Err:   Msg = "Error #: " & Format$(Err.Number) & vbCrLf   Msg = Msg & Err.Description   Err.Raise vbObjectError, "clsTest.AddInvoice", Msg   Resume AddInvoice_EndEnd 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.

  2. Save and close the clsTest class module.
  3. Open the Orders form in Design view.
  4. On the View menu, click Code, and then type the following procedure:
    Public Function SetShipTo() As Boolean   Call CustomerID_AfterUpdate   SetShipTo = TrueEnd 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.

  5. Close and save the Orders form.
The class module also supports a Terminate event. This event triggers whena Class object falls out of scope, or when it is unloaded from memory bysetting its object variable equal to Nothing. The Terminate event is veryimportant because you use it to clean up any objects or references that theclass itself initiated. For C++ programmers, this is similar to aDestructor.

Follow these steps to create a Terminate event in the clsTest class modulethat closes the Orders form and unloads the This_frm object variable:
  1. Open the clsTest class module in Design view.
  2. Select Class in the Object box of the module window.
  3. Select Terminate in the Procedure box of the module window.
  4. 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:
  1. Create a new standard module and save it as Module1.
  2. 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 = TrueEnd Function					
  3. To test this function, type the following line in the Immediate window, and then press ENTER.
    Note that the function does the following:

    1. Displays a message box indicating that the class has been Initialized.
    2. Opens the Orders form and displays a blank invoice for CustomerID ALFKI.
    3. Displays a message box indicating that the RecordActive=OrderId, where OrderID is the number automatically assigned to the new order.
    4. Closes the Orders form.
    5. Displays a message box indicating that the class has been Terminated.
For more information about class modules, click Microsoft Access Help on the Help menu, type create a class module that is not associated with a form or report in the Office Assistant or the Answer Wizard, and then click Search to view the topic.

Article ID: 209968 - Last Review: 12/05/2015 11:16:07 - Revision: 2.2

Microsoft Access 2000 Standard Edition

  • kbnosurvey kbarchive kbinfo kbprogramming kbusage KB209968