Whereas implicit variable declaration can initially make your code easier to write, explicit variable declaration ultimately makes the code easier to read, modify, debug, and run. To explicitly declare a variable, you use the Dim, Private, Public, or Static keyword to specify the variable's scope (what parts of your macro can use the variable), lifetime (how long Visual Basic keeps data in the variable), and data type (what kind of information the variable contains).
Explicit variable declaration:
To reduce t
Tip
To reduce the amount of time you spend deciphering, debugging, and running code, explicitly declare each variable and specify as much information as you can about the data to be stored in it.
The simplest form of explicit variable declaration creates a new variable with the Variant data type and procedure-level scope. The value in the variable is preserved only while the procedure is running. The following example declares two variables — radius and area.
Sub CircleArea() Dim radius, area radi us = InputBox("Circle Radius?") area = 3.14159 * radius ^ 2 MsgBox "The area is " & area End Sub
You'll learn more about using declaration statements to specify variable scope, lifetime, and data type later in this chapter.