Custom data types are a great way to store more than one related value for an item,
but they have a few shortcomings. They don??™t do any validation, they cannot perform actions
(methods or functions), and they cannot by themselves trigger events. Classes allow you to do
all of these.
The cEmployee Class
Let??™s take a quick look at the Employee data type from our previous example:
Type Employee
ID As Long
Name As String
Title As String
Phone As String
End Type
The first thing we will do is create properties for each value type. In Visual Basic 5/6.0
and VBA, you must create methods for getting and setting the values of a property. These are
known as Property Let and Property Get methods. A third method is available if your property
will return or set an object. This is known as the Property Set method, and it works in a
similar manner to the Property Let method.
1. In a new workbook open the VBE and insert a class module (choose Insert ?¤ Class
Module).
2. In the Property Sheet, rename the class module cEmployee.
3. In the code pane, enter the following code:
Dim m_lngID As Long
Dim m_sName As String
Dim m_sTitle As String
Dim m_sPhoneNumber As String
These module-level variables will contain the values for our object.
4. Next, enter the Property Let and Get functions for each property:
Property Get ID() As Long
ID = m_lngID
End Property
Property Let ID(newID As Long)
m_lngID = newID
End Property
CHAPTER 1 n THE MACRO RECORDER AND CODE MODULES 31
Property Get Name() As String
Name = m_sName
End Property
Property Let Name(newName As String)
m_sName = newName
End Property
Property Get Title() As String
Title = m_sTitle
End Property
Property Let Title(newTitle As String)
m_sTitle = newTitle
End Property
Property Get PhoneNumber() As String
PhoneNumber = m_sPhoneNumber
End Property
Property Let PhoneNumber(newPhoneNumber As String)
m_sPhoneNumber = newPhoneNumber
End Property
Note that the module-level variables are used within each Property Let or Get method,
and are either being returned (Get) or assigned a value (Let).
Pages:
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58