Microsoft Office Tutorials and References
In Depth Information
Using Comments in Your Code
Forcing yourself to declare all variables
To force yourself to declare all the variables that you use, include the following as the first
instruction in your VBA module:
Option Explicit
This statement causes your procedure to stop whenever VBA encounters an undeclared variable
name. VBA issues an error message ( Compile error: Variable not defined ), and you
must declare the variable before you can proceed.
To ensure that the Option Explicit statement appears in every new VBA module
automatically, enable the Require Variable Declaration option on the Editor tab of the VB Editor Options
dialog box. To display this dialog box, choose Tools➜Options.
The second statement declares two constants with a single statement, but it does not declare a
data type. Consequently, the two constants are variants. Because a constant never changes its
value, you normally want to declare your constants as a specific data type. The scope of a
constant depends on where it is declared within your module:
h To make a constant available within a single procedure only, declare it after the Sub or
Function statement to make it a local constant.
h To make a constant available to all procedures in a module, declare it before the first
procedure in the module.
h 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. The following statement
creates a constant that is valid in all VBA modules in the workbook:
Public Const AppName As String = “Budget Tools”
If you attempt to change the value of a constant in a VBA procedure, you get an error —
as 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 makes your code more readable
and makes it easier to change should the need arise — you have to change only one instruction
rather than several.
VBA and Excel define many constants that you can use in your code without declaring them. For
example, the following statement uses a constant named vbInformation :
MsgBox “Hello”, vbInformation
Search JabSto ::

Custom Search