Alvechurch Data - Enumerated constants in VB

Visual Basic is full of enumerated constants that make programming easier; the color value 16711680 is obscure but the color vbBlue is obvious. You can add your own enumerated constants for values used within your own organisation and make your own code more reliable and easier to maintain.

By default, enumerated constants hold a series of consecutive longs starting from zero. This example assigns values 0 to 3 to four security levels:

Public Enum SecLevels
  sleAdmin
  slePowerUser
  sleUser
  sleGuest
End Enum

The security routines in the rest of the application can now refer to sleAdmin and the other constants instead of their numeric values. The three-letter lower case prefix helps you recognise the constant as part of this enumerated set when you see it in code.

VB does not add the End Enum automatically and will give an error if you leave it out. Type it in before adding the members so that you don't forget it.

Values do not have to be consecutive, you can override this default by assigning particular values:

Public Enum SecColors
  scoPink = &HC0C0FF
  scoYellow = &HC0FFFF
  scoGreen = &HC0DEC0
  scoLilac = &HFFD4D4
End Enum

You can mix the automatic and override methods of numbering to get broken sequences like 0, 1, 2, 8, 9, 10 but the declaration is easier to understand if you explicitly override every value.

Enumerated constants are public by default because they are usually used to provide consistent values throughout an application. It does no harm to declare them as Public to remind yourself that they do have global scope and that their names may clash with something inside another module.

If you do have a clash of enumerated names then you can resolve the conflict by giving the full name. A constant named Trunk might refer to a constant belonging to a car, a body, or a tree:

Auto.Trunk
Body.Trunk
Tree.Trunk

Enumerated constants are shown in the Object Browser. This helps you when you forget the names but is more helpful when another developer is using the ActiveX component you have written.

Top of page
VB Tips