Académique Documents
Professionnel Documents
Culture Documents
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.
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