Declaring Constants

You declare constants with the Const statement. Here are some examples:

Const NumQuarters as Integer = 4

Const ModName as String = "Budget Macros"

Public Const AppName as String = "Budget Application"

The second example doesn't declare a data type. Consequently, VBA determines the data type from the value. The Rate variable is a Double, and the Period variable is an Integer. Because a constant never changes its value, you'll normally want to declare your constants as a specific data type.

Like variables, constants also have a scope. If you want a constant to be available within a single procedure only, declare it after the Sub or Function statement to make it a local constant. To make a constant available to all procedures in a module, declare it before the first procedure in the module. To make a constant available to all modules in the workbook, use the Public keyword, and declare the constant before the first procedure in a module. For example:

Public Const InterestRate As Double = 0.0725

If you attempt to change the value of a constant in a VBA procedure, you get an error — which is what you would expect. A constant is a constant, not a variable.

Using constants throughout your code in place of hard-coded values or strings is an excellent programming practice. For example, if your procedure needs to refer to a specific value (such as an interest rate) several times, it's better to declare the value as a constant and use the constant's name rather than its value in your expressions. This technique not only makes your code more readable, it also makes it easier to change should the need arise — you have to change only one instruction rather than several.

Was this article helpful?

0 0

Post a comment