You often need to create a set of related constants, and Chapter 5 discussed using enumerated types, or enums for that purpose. In class modules, you often use enumerated types in property procedures and methods.
Recall that in the clsClassroom class, provision was made for a clsTeacher class — after all, it wouldn't be much of a classroom if it didn't have a teacher. To assign the grade level that a teacher will teach and to provide some measure of automation and consistency in the assignment process, you'd set up some enumerated types for specifying the grades to which you may want to assign the teachers.
Public Enum GradeLevel glFreshman glSophomore glJunior glSenior End Enum
Notice that in the previous example, no values were specified 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, glFreshman will have a value of 0, glSophomore is 1, and so on. If you want to explicitly declare values, you can, like so:
Public Enum GradeLevel glFreshman = 0 glSophomore = 1 glJunior glSenior = 3 End Enum
In this code, the constants for which a value is specified will have that value, but notice that one of them (glJunior) has no value specified. Its value is determined by the value of its preceding member, so in this case, glJunior will have a value of 2. Try changing the value of glSophomore to 123 and test it to see what glJunior's value will be.
Once you've defined the constants you need, simply 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 shown in Figure 13-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 13-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 lf..Then or Select Case..End Case constructs. For example,
Public Property Let GradeLevel(lngLevel As GradeLevel) Select Case lngLevel
Case glFreshman, glSophomore, glJunior, glSenior mlngLevel = lngLevel Case Else
' Do something when the wrong grade is assigned End Select End Property
Because enum values are numbers, you can also perform numeric comparisons using named values. For example:
Public Property Let GradeLevel(lngLevel As GradeLevel)
If lngLevel >= glFreshman And lngLevel <= glSenior Then mlngLevel = lngLevel
' Do something when the wrong grade is assigned End If End Property
Was this article helpful?