ACC97: Introduction to Stand-Alone Class Module Programming

ID: Q160007

The information in this article applies to:

SUMMARY

Advanced: Requires expert coding, interoperability, and multiuser skills.

This article describes how to conceptualize and implement stand-alone class modules in Microsoft Access 97. Microsoft Access introduced class modules in Microsoft Access 7.0, where class modules behind forms and reports allow you to create procedures that define custom methods and properties for the object.

Microsoft Access 97 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.

This article assumes that you are familiar with Visual Basic for Applications and with creating Microsoft Access applications using the programming tools provided with Microsoft Access. For more information about Visual Basic for Applications, please refer to the "Building Applications with Microsoft Access 97" manual.

MORE INFORMATION

Class modules have the following characteristics:

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 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: The details of what this code accomplishes are not apparent from the code sample. 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: Following the steps in this example will modify the sample database Northwind.mdb. You may want to back up the Northwind.mdb file and perform 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 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 String
     Private This_frm As Form

5. Select Class in the Object box of the module window. "Initialize" is
   automatically selected in the Procedure box.

6. Type the following procedure:

     Private Sub Class_Initialize()
        This_ClassState = "Initialized"
     End Sub

7. Type 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 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:

1. Create the following in the 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 code 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 allows the caller of the class to handle any errors instead
   of a user.

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 = 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 in order
   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 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:

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. Type 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 = True
      End Function

3. To test this function, type the following line in the Debug window,
   and then press ENTER.

      ?CreateClass1()

   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.

REFERENCES

For more information about class modules, search the Help Index for "class modules," or ask the Microsoft Access 97 Office Assistant.

Additional Query Words:

Keywords          : kbprg kbusage
Version           : 97
Platform          : WINDOWS
Hardware          : x86
Issue type        : kbhowto

Last Reviewed: November 20, 1998