Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (5.72 MB, 490 trang )
Dim dt As Date
dt = #1/2/97#
A symbolic constant (also sometimes referred to simply as a constant) is a name for a literal
constant.
To define or declare a symbolic constant in a program, we use the Const keyword, as in:
Const InvoicePath = "d:\Invoices\"
In this case, Excel will replace every instance of InvoicePath in our code with the string
"d:\Invoices\". Thus, InvoicePath is a constant, since it never changes value, but it is not
a literal constant, since it is not used as written.
The virtue of using symbolic constants is that, if we decide later to change "d:\Invoices\" to
"d:\OldInvoices\", we only need to change the definition of InvoicePath to:
Const InvoicePath = "d:\OldInvoices\"
rather than searching through the entire program for every occurrence of the phrase
"d:\Invoices\".
It is generally good programming practice to declare any symbolic constants at the beginning of
the procedure in which they are used (or in the Declarations section of a code module). This
improves readability and makes housekeeping simpler.
In addition to the symbolic constants that you can define using the Const statement, VBA has a
large number of built-in symbolic constants (about 700), whose names begin with the lowercase
letters vb. Excel VBA adds additional symbolic constants (1266 of them) that begin with the
letters xl. We will encounter many of these constants throughout the book.
Among the most commonly used VBA constants are vbCrLf, which is equivalent to a carriage
return followed by a line feed, and vbTab, which is equivalent to the tab character.
5.3.1 Enums
Microsoft has recently introduced a structure into VBA to categorize the plethora of symbolic
constants. This structure is called an enum , which is short for enumeration. A list of enums can be
obtained using my Object Model Browser software. For instance, among Excel's 152 enums, there
is one for the fill type used by the AutoFill method, defined as follows:
Enum XlAutoFillType
xlFillDefault = 0
xlFillCopy = 1
xlFillSeries = 2
xlFillFormats = 3
xlFillValues = 4
xlFillDays = 5
xlFillWeekdays = 6
xlFillMonths = 7
xlFillYears = 8
xlLinearTrend = 9
xlGrowthTrend = 10
End Enum
40
(The Excel documentation incorrectly refers to this enum as XlFillType.) Note that enum
names begin with the letters Xl (with an uppercase X ).
Thus, the following line of code will autofill the first seven cells in the first row of the active sheet
with the days of the week, assuming that the first cell contains the word Monday:
ActiveSheet.Range("A1").AutoFill ActiveSheet.Range("A1:G1"),
xlFillDays
This is far more readable than:
ActiveSheet.Range("A1").AutoFill ActiveSheet.Range("A1:G1"), 5
Note that this enum is built in, so we do not need to add it to our programs in order to use these
symbolic constants. (We can create our own enums, but this is generally not necessary in Excel
VBA programming, since Excel has done such a good job of this for us.)
As another example, the built-in enum for the constant values that can be returned when the user
dismisses a message box (by clicking on a button) is:
Enum VbMsgBoxResult
vbOK = 1
vbCancel = 2
vbAbort = 3
vbRetry = 4
vbIgnore = 5
vbYes = 6
vbNo = 7
End Enum
For instance, when the user hits the OK button on a dialog box (assuming it has one), VBA returns
the value vbOK. Certainly, it is a lot easier to remember that VBA will return the symbolic
constant vbOK than to remember that it will return the constant 1. (We will discuss how to get and
use this return value later.)
VBA also defines some symbolic constants that are used to set the types of buttons that will
appear on a message box. These are contained in the following enum (which includes some
additional constants not shown):
Enum VbMsgBoxStyle
vbOKOnly = 0
vbOKCancel = 1
vbAbortRetryIgnore = 2
vbYesNoCancel = 3
vbYesNo = 4
vbRetryCancel = 5
End Enum
To illustrate, consider the following code:
If MsgBox("Proceed?", vbOKCancel) = vbOK Then
' place code to execute when user hits OK button
Else
' place code to execute when user hits any other button
End If
41
In the first line, the code MsgBox("Proceed?", vbOKCancel) causes Excel to display a
message box with an OK button and a Cancel button and the message "Proceed?", as shown in
Figure 5-1.
Figure 5-1. Example message box
If the user clicks the OK button, Excel will return the constant value vbOK; otherwise it will return
the value vbCancel. Thus, the If statement in the first line will distinguish between the two
responses. (We will discuss the If statement in detail in Chapter 8. Here, we are interested in the
role of symbolic constants.)
In case you are not yet convinced of the value of symbolic constants, consider the following enum
for color constants:
Enum ColorConstants
vbBlack = 0
vbBlue = 16711680
vbMagenta = 16711935
vbCyan = 16776960
vbWhite = 16777215
vbRed = 255
vbGreen = 65280
vbYellow = 65535
End Enum
Consider which you'd rather type, this:
ATextBox.ForeColor = vbBlue
or this:
ATextBox.ForeColor = 16711680
Need I say more?
5.4 Variables and Data Types
A variable can be thought of as a memory location that can hold values of a specific type. The
value in a variable may change during the life of the program—hence the name variable.
In VBA, each variable has a specific data type, which indicates which type of data it may hold.
For instance, a variable that holds text strings has a String data type and is called a string variable.
A variable that holds integers (whole numbers) has an Integer data type and is called an integer
42
variable. For reference, Table 5-1 shows the complete set of VBA data types, along with the
amount of memory that they consume and their range of values. We will discuss a few of the more
commonly used data types in a moment.
Table 5-1. VBA Data Types
Type
Size in Memory
Range of Values
Byte
1 byte
0 to 255
Boolean
2 bytes
True or False
Integer
2 bytes
-32,768 to 32,767
Long (long integer) 4 bytes
-2,147,483,648 to 2,147,483,647
Single(single4 bytes
Approximately -3.4E38 to 3.4E38
precision real)
Double(double8 bytes
Approximately -1.8E308 to 4.9E324
precision real)
Currency(scaled
Approximately -922,337,203,685,477.5808
8 bytes
integer)
to 922,337,203,685,477.5807
Date
8 bytes
1/1/100 to 12/31/9999
Object
4 bytes
Any Object reference.
Variable length:10 bytes +
Variable length: <= about 2 billion (65,400
String
string length;Fixed length:
for Win 3.1) Fixed length: up to 65,400
string length
16 bytes for numbers22 bytes Number: same as DoubleString: same as
Variant
+ string length
String
User-defined
Varies
5.4.1 Variable Declaration
To declare a variable means to define its data type. Variables are declared with the Dim keyword
(or with the keywords Private and Public, which we will discuss later in this chapter). Here
are some examples:
Dim
Dim
Dim
Dim
Dim
Dim
Dim
Name As String
Holiday As Date
Age As Integer
Height As Single
Money As Currency
wbk As Workbook
ch As Chart
The general syntax of a variable declaration is:
Dim VariableName As DataType
If a particular variable is used without first declaring it, or if it is declared without mentioning a
data type, as in:
Dim Age
then VBA will treat the variable as having type Variant. As we can see from Table 5-1, this is
generally a waste of memory, since variants require more memory than most other types of
variables.
43
For instance, an integer variable requires 2 bytes, whereas a variant that holds the same integer
requires 16 bytes, which is a waste of 14 bytes. It is not uncommon to have hundreds or even
thousands of variables in a complex program, and so the memory waste could be significant. For
this reason, it is a good idea to declare all variables.
Perhaps more importantly, much more overhead is involved in maintaining a Variant than its
corresponding String or Integer, for example. This in turn means that using Variants typically
results in worse performance than using an equivalent set of explicit data types.
We can place more than one declaration on a line to save space. For instance, the following line
declares three variables:
Dim Age As Integer, Name As String, Money As Currency
Note, however, that a declaration such as:
Dim Age, Height, Weight As Integer
is legal, but Age and Height are declared as Variants, not Integers. In other words, we must
specify the type for each variable explicitly.
It is also possible to tell VBA the type of the variable by appending a special character to the
variable name. In particular, VBA allows the type-declaration suffixes shown in Table 5-2. (I
personally dislike these suffixes, but they do save space.)
Suffix
%
&
!
#
@
$
Table 5-2. Type-Declaration Suffixes
Type
integer
long
single
double
currency
string
For instance, the following line declares a variable called Name$ of type String:
Dim Name$
We can then write:
Name$ = "Donna"
Finally, let us note that although Excel allows variable and constant declarations to be placed
anywhere within a procedure (before the item is used, that is), it is generally good programming
practice to place all such declarations at the beginning of the procedure. This improves code
readability and makes housekeeping much simpler.
5.4.2 The Importance of Explicit Variable Declaration
We have said that using the Variant data type generally wastes memory and often results in poorer
performance. There is an additional, even more important reason to declare all variables explicitly.
This has to do with making typing errors, which we all do from time to time. In particular, if we
accidentally misspell a variable name, VBA will think we mean to create a new variable!
44
To illustrate how dangerous this can be, consider the NewBook procedure in Example 5-1, whose
purpose is to take the first open workbook, change its contents, ask the user for a name under
which to save the changed workbook, and then save the workbook under the new name.
Example 5-1. A Procedure with a Typo
Sub NewBook()
Dim Wbk As Workbook
Dim WbkName As String
' Get first open workbook
Set Wbk = Workbooks(1)
' Get the workbook name
WbkName = Wbk.Name
' Code to change the contents of the workbook
' goes here . . .
' Ask user for new name for document
WkbName = InputBox("Enter name for workbook " & WbkName)
' Save the workbook
Wbk.SaveAs WbkName
End Sub
Observe that there is a typographical error (the b and k are transposed) in the following line:
WkbName = InputBox("Enter name for workbook " & WbkName)
Since the variable WkbName is not declared, Excel will treat it as a new variable and give it the
Variant data type. Moreover, VBA will assume that we want the new filename to be assigned to
the variable WkbName, and will save the changed document under its original name, which is
stored in WbkName. Thus, we will lose the original workbook when it is inadvertently overwritten
without warning!
5.4.2.1 Option Explicit
To avoid the problem described in the previous example, we need a way to make Excel refuse to
run a program if it contains any variables that we have not explicitly declared. This is done simply
by placing the line:
Option Explicit
in the Declarations section of each code module. Since it is easy to forget to do this, VBA
provides an option called "Require Variable Declaration" in its Options dialog box. When this
option is selected, VBA automatically inserts the Option Explicit line for us. Therefore, I
strongly recommend that you enable this option.
Now let us briefly discuss some of the data types in Table 5-1.
5.4.3 Numeric Data Types
The numeric data types include Integer, Long, Single, Double, and Currency. A long is also
sometimes referred to as a long integer.
45
5.4.4 Boolean Data Type
A Boolean variable is a variable that takes on one of two values: True or False. This is a very
useful data type that was only recently introduced into VBA. Prior to its introduction, VBA
recognized 0 as False and any nonzero value as True, and you may still see this usage in older
code.
5.4.5 String Data Type
A string is a sequence of characters. (An empty string has no characters, however.) A string may
contain ordinary text characters (letters, digits, and punctuation) as well as special control
characters such as vbCrLf (carriage return/line feed characters) or vbTab (tab character). As we
have seen, a string constant is enclosed within quotation marks. The empty string is denoted by a
pair of adjacent quotation marks, as in:
EmptyString = ""
There are two types of string variables in VBA: fixed-length and variable-length. A fixed-length
string variable is declared as follows:
Dim FixedStringVarName As String * StringLen
For instance, the following statement declares a fixed-length string of length 10 characters:
Dim sName As String * 10
Observe that the following code, which concatenates two strings:
Dim s As String * 10
s = "test"
Debug.Print s & "/"
and produces the output:
test
/
This shows that the content of a fixed-length string is padded with spaces in order to reach the
correct length.
A variable-length string variable is a variable that can hold strings of varying lengths (at different
times, of course). Variable-length string variables are declared simply as:
Dim VariableStringVarName As String
As an example, the code:
Dim s As String
s = "test"
Debug.Print s & "/"
s = "another test"
Debug.Print s & "/"
produces the output:
46