Freigeben über


Visual Basic Concepts

Class Module Step by Step

This example shows how you can use class modules to define classes, from which you can then create objects. It will also show you how to create properties and methods for the new class, and demonstrate how objects are created and destroyed.

Open a new Standard Exe project, and insert a class module by selecting Add Class Module from the Project menu. Draw four command buttons on the form. The following table lists the property values you need to set for the objects in this example.

Object Property Setting
Class module Name Thing
Command1 Caption Show the Thing
Command2 Caption Reverse the Thing's Name
Command3 Caption Create New Thing
Command4 Caption Temporary Thing

Note   Class modules are saved in files with the extension .cls.

In the class module Declarations section, add the following:

Option Explicit
Public Name As String
Private mdtmCreated As Date

The variable Name will be a property of the Thing object, because it's declared Public.

Note   Don't confuse this Name property with the Name property of the class module, which the table above instructed you to set. (The Name property of the class module gives the Thing class its name.) Why would you give the Thing class a Name property? A better question might be, why not? You may want to give the Thing class a Name property because Things should have names! Remember that there's nothing special about the property and method names Visual Basic uses. You can use those same property and method names for your classes.

The variable mdtmCreated is a private data member that is used to store the value of the read-only Created property. The Created property returns the date and time a Thing object was created. To implement the Created property, add the following Property Get to the Declarations section of the class module:

Property Get Created() As Date
   Created = mdtmCreated
End Property

Note   If you added the property procedure using the Add Procedure dialog box, on the Tools menu, be sure to delete the Property Let declaration that is automatically added by this dialog. Property Let is only required for read-write properties, as explained in "Putting Property Procedures to Work for You."

The Thing object has one method, ReverseName, which simply reverses the order of the letters in the Name property. It doesn't return a value, so it's implemented as a Sub procedure. Add the following Sub procedure to the class module.

Public Sub ReverseName()
   Dim intCt As Integer
   Dim strNew As String
   For intCt = 1 To Len(Name)
      strNew = Mid$(Name, intCt, 1) & strNew
   Next
   Name = strNew
End Sub

Class modules have two events, Initialize and Terminate. In the Object drop down of the class module, select Class. The Procedure drop down will show the events. Place the following code in the event procedures:

Private Sub Class_Initialize()
   ' Set date/time of object creation, to be returned
   '    by the read-only Created property.
   mdtmCreated = Now
   ' Display object properties.
   MsgBox "Name: " & Name & vbCrLf & "Created: " _
   & Created, , "Thing Initialize"
End Sub

Private Sub Class_Terminate()
   ' Display object properties.
   MsgBox "Name: " & Name & vbCrLf & "Created: " _
   & Created, , "Thing Terminate"
End Sub

Usually, the Initialize event procedure contains any code that needs to be executed at the moment the object is created, such as providing the time stamp for the Created property. The Terminate event contains any code you need to execute in order to clean up after the object when it is being destroyed.

In this example, the two events are being used primarily to give you a visual indication that a Thing object is being created or destroyed.

Using the Thing Object

Add this declaration to the Declarations section of the form module:

Option Explicit
Private mth As Thing

The variable mth will hold a reference to a Thing object, which will be created in the form's Load event. Put the following code in the Form_Load event procedure, and in the Click event procedures for the four buttons.

Private Sub Form_Load()
   Set mth = New Thing
   mth.Name = InputBox("Enter a name for the Thing")
End Sub

' Button "Show the Thing"
Private Sub Command1_Click()
   MsgBox "Name: " & mth.Name & vbCrLf _
   & "Created: " & mth.Created, , "Form Thing"
End Sub

' Button "Reverse the Thing's Name"
Private Sub Command2_Click()
   mth.ReverseName
   ' Click "Show the Thing"
   Command1.Value = True
End Sub

' Button "Create New Thing"
Private Sub Command3_Click()
   Set mth = New Thing
   mth.Name = InputBox( _
   "Enter a name for the new Thing")
End Sub

' Button "Temporary Thing".
Private Sub Command4_Click()
   Dim thTemp As New Thing
   thTemp.Name = InputBox( _
   "Enter a name for the Temporary Thing")
End Sub

Running the Project

Press F5 to run the project. Looking at the code in the Form_Load event procedure, you can see that the New operator is used to create a Thing object. A reference to this Thing is assigned to the variable mth.

You will see the InputBox asking you for a name for the Thing. When you type a name and press ENTER, the return value is assigned to the Name property of the Thing object.

Show the Form Thing

You can verify that the Name property has been assigned by pressing the first button, "Show the Thing," which displays a message box with all the properties of the Thing object.

Reverse the Thing's Name

Press the second button, "Reverse the Thing's Name." This button calls the ReverseName method to turn the Thing object's name around, and then clicks the first button to display the updated property values.

Create New Thing

Click the "Create New Thing" button to destroy the existing Thing object and create a new one. (Or, as it turns out, to create a new Thing and then destroy the old one.)

The New operator causes a new Thing to be created, so you'll see the MsgBox displayed by the new Thing's Initialize event. When you click OK, a reference to the new Thing is placed in the form-level variable mth.

This wipes out the reference to the old Thing. Because there are no more references to it, it's destroyed, and you'll see its Terminate event message box. When you click OK, the InputBox statement requests a name for the new Thing.

Note   If you want to destroy the old Thing before creating the new one, you can add the line of code Set mth = Nothing at the beginning of the event procedure.

Temporary Thing

The fourth button demonstrates another aspect of object lifetime. When you press it, you'll be prompted for a name for the temporary Thing.

But wait — there isn't a temporary Thing object yet. You haven't seen its Initialize message box. How can you assign it a name?

Because the variable thTemp was declared As New, a Thing object will be created the moment one of its properties or methods is invoked. This will happen when the return value of the InputBox is assigned to the Name property. Type a name and click OK on the InputBox.

You'll now see the Thing Initialize message box, which shows you that the Name property is still blank. When you click OK to dismiss the message box, the value from the InputBox statement is finally assigned to the Name property. That's a lot of activity for one line of code.

Of course, as soon as you've done that, the Click event procedure ends, and the variable thTemp goes out of scope. The object reference for the temporary Thing is released, so you'll see the Thing Terminate message box. Notice that it contains the name you supplied.

Each time you click this button, another temporary Thing will be created, named, and destroyed.

Closing the Program

Close the program by clicking the form's close button. Do not use the End button on the toolbar. When the program closes, Form1 is destroyed. The variable mth goes out of scope, and Visual Basic cleans up the reference to the Thing. There are no remaining references to the Thing, so it's destroyed, and its Terminate event message box is displayed.

Run the program again, and this time end it using the End button on the toolbar. Notice that the Terminate message box for the Thing object is not displayed.

It's important to remember that ending your program with the End button, or with an End statement in your code, halts the program immediately, without executing the Terminate events of any objects. It's always better to shut down your program by unloading all the forms.

You may find it useful to run the example by pressing F8 to step through the code one line at a time. This is a good way to understand the order of events for object creation and destruction.

Important   In an actual application, the Initialize and Terminate events should not contain message boxes, or any other code that allows Windows messages to be processed. In general, it's better to use Debug.Print statements when debugging object lifetimes.

For More Information   Forms and controls are a bit different from other objects, as discussed in "Life Cycle of Visual Basic Forms."

You can read more about what you can do with classes and class modules in "Adding Properties and Methods to a Class" and "Adding Events to a Class."