Microsoft Office Tutorials and References
In Depth Information
Using Comments in Your Code
Unlike some languages, VBA does not permit you to declare a group of variables to
be a particular data type by separating the variables with commas. For example, the
following statement — although valid — does not declare all the variables As Longs:
Dim i, j, k As Long
In the preceding statement, only k is declared to be an integer. To declare all variables
As Longs, use this statement:
Dim i As Long, j As Long, k As Long
If you don’t declare the data type for a variable that you use, VBA uses the default data type —
Variant . Data stored as a variant acts like a chameleon: It changes type depending on what you
do with it. The following procedure demonstrates how a variable can assume different data types:
Function VARIANT_DEMO()
MyVar = “123”
MyVar = MyVar / 2
MyVar = “Answer: “ & MyVar
VARIANT_DEMO = MyVar
End Function
In the VARIANT_DEMO Function procedure, MyVar starts out as a three-character text string
that looks like a number. Then this string is divided by two, and MyVar becomes a numeric data
type. Next, MyVar is appended to a string, converting MyVar back to a string. The function
returns the final string: Answer: 61.5 .
You’ll notice that I don’t follow my own advice in this chapter. In many of the
subsequent function listings in this chapter, I don’t declare the variables used. I omitted the
variable declarations to keep the code simple so that you can focus on the concept
being discussed. In the code examples on the companion CD-ROM, I always declare
the variables.
Using constants
A variable’s value may — and often does — change while a procedure is executing. That’s why it’s
called a variable. Sometimes, you need to refer to a named value or string that never changes: in
other words, a constant.
You declare a constant by using the Const statement. Here are some examples:
Const NumQuarters As Long = 4
Const Rate = .0725, Period = 12
Const CompanyName as String = “Acme Snapholytes”
 
Search JabSto ::




Custom Search