By now, you should be quite familiar with Intellisense and its benefits. One benefit is that when you type the name of a property or a method whose value should be set to one of a set of constants, the list of appropriate constants automatically appears. For example, when using the OpenForm method of the DoCmd object, a list of six intrinsic constants appears for the View parameter. Using enumerated types, you can benefit from this behavior with your own custom properties and methods.
Here's how it works: For the custom PersonType property, imagine that only four values are appropriate: Client, PersonalContact, Vendor, and Other. Using an enumerated type, you can easily set it up so that the four appropriate types appear in a list whenever you set the PersonType property of the class. Use the Enum keyword to define an enumerated type:
'Enumeration for PersonType Public Enum PersonTypeList Client PersonalContact Vendor Other End Enum
To use the enumerated type with the property, you must include it in the definition of the Property Get and Property Let routines:
Public Property Get PersonType() As PersonTypeList 'Retrieve the PersonType property PersonType = mlngPersonType End Property Public Property Let PersonType(ByVal lngPersonType As PersonTypeList) 'Set the PersonType property mlngPersonType = lngPersonType End Property
Whenever you attempt to set the value of the PersonType property of the class, the list of valid types automatically appears (see Figure 13.2).
Notice that the code uses a long integer to store the person type. This is because VBA limits
all enumerated type constants to long integer values. Furthermore, you might wonder what values are stored in the variable when you use each constant. Unless directed otherwise, VBA assigns the first item in the list the value 0 (zero). It assigns each subsequent item in the list the next value (1, 2, 3, and so on). In this example, VBA assigns the Client 0, the PersonalContact 1, the Vendor 2, and Other 3. If you wish to control the long integer value assigned to each item in the list, simply set the constant equal to a value:
Enumeration for PersonType Public Enum PersonTypeList2 Client = 10 PersonalContact = 5 Vendor = 2 Other = 999 End Enum
There is one additional aspect of enumerated types that is worth noting. The process of defining an enumerated type does not ensure that only valid values are used for the property or method. Although Intellisense provides a list of the constants included in the enumerated type, any value can be entered.