Outline

  Using constants
 The enum keyword
 

Your current position:
Home 
  Visual Basic
    Programming Basics
     
Constants

Constants

 

The dictionary provides the following definition:
constant
_adj.
1
  continuous (needs constant attention).
2
  occurring frequently (receive constant complaints).
3
  (often foll. by to) unchanging, faithful, dependable.
_n.
1
  anything that does not vary.
2
  Math. a component of a relationship between variables that does not change its value.
3
  Physics a a number expressing a relation, property, etc., and remaining the same in all circumstances. b such a number that remains the same for a substance in the same conditions.

 

Using constants

Your code might contain frequently occurring constant values, or might depend on certain numbers that are difficult to remember and have no obvious meaning. You can make your code easier to read and maintain using constants. A constant is a meaningful name that takes the place of a number or string that does not change. You can't modify a constant or assign a new value to it as you can a variable.

In Visual Basic there are three kinds of constants.

1. Intrinsic constants – declared in Visual Basic (e.g.:vbReadOnly,vbRed etc.)

2. Object libraries – declared in libraries that your project uses.

3. User defined – declared by the user.

 

To get a complete list of constants in your project use the Object browser. You can access the Object browser by pressing the F2 key on your keyboard or by selecting it form the View menu.

The intrinsic constants supplied by all objects appear in a mixed-case format, with a 2-character prefix indicating the object library that defines the constant. Constants from the Visual Basic for Applications object library are prefaced with "vb" and constants from the Microsoft Excel object library are prefaced with "xl" and so on.

Constants are declared in Visual Basic using the “Const” keyword:

Const [constant name] As [constant type] = [value]

Example:
Const MAH_HEIGHT = 300

The Enum Keyword

If you use many constants that relate to a single place it’s recommended that you use enumerations of constants. You can do this using the Enum keyword of Visual Basic.

Syntax:

 

Enum [enumeration name]

    [constant 1] = [value 1]

    [constant 2] = [value 2]

    [constant 3] = [value 3]

   

    [constant n] = [value n]

End Enum

 

Example:

Enum VideoMode

    vm640x480 = 1

    vm800x600 = 2

    vm1024x768 = 3

End Enum

 

Note: Enum keyword cannot be used inside a function or procedure. It should be declared in general mode. Otherwise you will receive an “Invalid inside procedure” error.

 

We will review this keyword later in the next chapter after you learn how to use objects and have used defined types.