Class Modules

Class Modules are very similar to UserForms except that they have no user interface and do not respond to any user-initiated events. You use Class Modules to create your own custom objects. Code written within the Class Module implements the object's properties and methods. Once you have written the code for your Class Module, you create instances of it by using the New keyword.

The following simple example demonstrates the use of Class Modules to create new objects. In this example, we will create a new object named MyClass, which has two properties, Title and DateCreated, and one method, TitleLength.

Open a new workbook and use the VBE to add one Standard Module and one Class Module. Using the Project Properties window, name the Class Module MyClass. Place the following code in MyClass:

Public Title As String
Private datDate As Date

Property Get DateCreated() As Date
   DateCreated = datDate
End Property

Private Sub Class_Initialize()
    datDate = Now
End Sub

Public Function TitleLength() As Integer
    TitleLength = Len(Title)
End Function

Now place the following procedure in the Standard Module:

Private clsMyClass As New MyClass

Sub CreateMyClassObject()
    clsMyClass.Title = "My Title"
    MsgBox "MyClass Title = " & clsMyClass.Title & _
        Chr(13) & "Title Length = " & _
        clsMyClass.TitleLength & Chr(13) & _
        "Date Created = " & clsMyClass.DateCreated
    Set clsMyClass = Nothing
End Sub

When you run the CreateMyClassObject procedure, the code creates a new instance of MyClass assigned to the variable clsMyClass and sets the Title property of the new object. The code then uses a message box to display the Title and DateCreated properties, as well as the TitleLength method of the object.