Using Enumerated Types with Properties and Methods

In VBA, we often need to create a set of related constants, and in Chapter 4 we discussed using enumerated types, or enums for that purpose. In class modules, we often use enumerated types in property procedures.

Recall that in the clsKennel class, we made provision for a clsGate class; after all, it wouldn't be much of a kennel if it didn't have a gate or two. Let's say that we want to color-code the kennel gates: red for big dangerous breeds, yellow for the less dangerous ones, and then blue and white for the least nasty breeds. To provide some measure of automation and consistency in the color selection process, let's set up some enumerated types for specifying the colors you may want to use on the kennel gates.

Public Enum GateColor gcRed gcYellow gcBlue gcWhite End Enum

Notice that in the above example, we haven't specified a value for any of the constants. This is perfectly acceptable because VBA automatically assigns a Long Integer value to each of them starting at zero and incrementing by one for each member specified. Therefore, gcRed will have a value of 0, gcYellow 1, and so on. If you want to explicitly declare values, you can, like so:

Public Enum GateColor gcRed = 0 gcYellow = 1 gcBlue gcWhite = 3 End Enum

In the above example, the constants for which I specified a value will have that value, but notice that one of them (gcBlue) has no value specified. Its value is determined by the value of its preceding member, so in this case, gcBlue will have a value of 2. Try changing the value of gcYellow to 123 and test it to see what gcBlue's value will be.

Once you've defined the constants you need, just use the enum as you would any other data type. As you type your definition into the editor, Intellisense displays your enum as one of the data type options, as in Figure 12-7.



Option Compare Database


Option Explicit

Private rastrColor ks String

Public Envrni GateColor

gcRed 4 0

gcYellow = 1


gcWliite = 3

End Enum

public property let Color (intcolor

as gate

SGateColor t




® Group

i® GroupLevs!


¿S Hyperlink





Figure 12-7

To use an enumerated value in your code, just begin typing the value assignment statement and Intellisense will do the rest, as shown in Figure 12-8.

Figure 12-8

Keep in mind that VBA allows you to specify values other than those listed by Intellisense, so your code needs to account for that possibility, perhaps using If...Then, or Select Case...End Case constructs. For example:

Public Property Let Color(intColor As GateColor) Select Case intColor

Case gcRed, gcYellow, gcBlue, gcWhite mstrColor = intColor Case Else

' Do something when the wrong color is selected End Select End Property

0 0

Post a comment