This chapter covers the basics of programming with variables, constants, and enumerations. Variables are used often in programming—they provide a way of storing and manipulating information. Variables come in several types, such as String variables for storing text, various numeric data types for storing numbers (for example, Integer variables for storing integer values), Date variables for storing dates and time, Boolean variables for storing
values, and even Object variables for storing objects.True/False
A constant is a named item that stores a value that doesn't change. Constants, like variables, exist only while a program is executing. Most programmers rarely create their own constants; they just use variables instead. However, there is another kind of constant that the programmer does not create but sometimes uses: Many useful constants are built into VBA to represent elements in Access, text color options in Excel, styles in Word, and so on. Here's an example showing how to turn a cell's contents red, using the
constant:vbRed
Range("A1").Font.Color = vbRed
For our purposes, the term enumeration means a numbered list—like a list of all the items you would need to buy to paint a room. In VBA, an enumerated list contains both the numbers and the names of the items so you can refer to each item either by its number in the list or by its name. Essentially, an enumeration is a group of related, predefined constants, but constants are more commonly identified by their names rather than their numbers. That's because the name
is easier to use in your programming than its number, 1312.AnimationFlyIntoFromLeft
The one type of variable that this chapter doesn't discuss is the Array variable, which is used to store a set of multiple pieces of related information at the same time. It's similar to an enumeration. Arrays, however, are so important in computer programming that I'll devote an entire chapter to them: Chapter 7, “Using Array Variables.”
Variables are used in nearly all computer programs, even short programs like our macros. Recall that you can think of a variable as a named area in the computer's memory that you use for storing data while a procedure is running. For example, in Chapter 5, “Understanding the Essentials of VBA Syntax,” you created a variable that stored a simple string of text that you then displayed in a message box:
myVariable = “Sample variable text"
MsgBox myVariable
The first statement sets aside an area in memory, names it
, and assigns the string myVariable
to it. The second statement retrieves the contents (called the value) of Sample variable text
from memory and uses the myVariable
function to display it in a message box. As long as your macro is running, the contents of MsgBox
will remain in the computer's memory. It's available if you want to use it again. You can even change the contents. In other words, the value in a variable can vary. A constant, by contrast, doesn't vary during program execution.myVariable
VBA imposes several constraints on how you name your variables:
Usually, you'll want to keep them much shorter than this so that you can easily type them into your code and so that your lines of code don't rapidly reach awkward lengths.
+
, –
, /
, *
), or comparison operators (=
, <>
, >
, >=
, <
, <=
), nor can they internally contain type-declaration characters (@
, &
, $
, #
). (You'll learn about the type-declaration characters later in this chapter.)User_Response
is one example.UserResponse
. This kind of case combination is known as camelCase (see Figure 6.1).As a general rule, you're pretty safe if you stick with straightforward alphanumerics enlivened by the occasional underscore if you like underscores.
For example, all of the following variable names are fine, although the last one is awkwardly long:
i
John
MyVariable
MissionParameters
The_String_the_User_Entered_in_the_Input_Box
On the other hand, these variable names are not usable:
My Variable
—Contains a spaceMy!Variable
—Contains an exclamation pointTime@Tide
—Contains a type-declaration character (@)1_String
—Does not start with a letterEach variable name must be unique within the scope in which it's operating (to prevent VBA from confusing it with any other variable). Typically, the scope within which a variable operates is a procedure, but if you declare the variable as public or private (discussed later in this chapter), its scope is wider.
The other constraint on variable names is that you should avoid assigning to a variable a name that VBA already uses as a command in its own language (such as
or Print
), or the name of a built-in function, statement, or object member. Doing so is called shadowing a VBA keyword.Stop
It doesn't necessarily cause problems, but it may prevent you from using that function, statement, or method without specifically identifying it to VBA by prefacing its name with
. For example, instead of VBA
, you'd have to use Date
—it's no big deal, but worth avoiding. After all, why add this complexity when it's simpler to just make up your own, unique variable names? Why do things that provide you with no real benefit and have drawbacks such as making your code harder to read? On top of that, if you forget to prepend the VBA, shadowing can cause bugs.VBA.Date
There's no reason to shadow a VBA keyword, but VBA has so many keywords that it's surprisingly easy to do so. Don't worry though about accidentally creating a variable name that violates one of the rules listed in this section. VBA will throw you an error message if you use @ or start your variable name with 6 or try any other illegal moves. VBA will either report “Invalid Character” or separate your variable name into multiple words, such as changing
into 56nin
, thinking you are trying to use line numbers in your code. (You can, if you like, number your lines, and VBA will execute the code by just ignoring the line numbers. I number the lines in the code in this book so I can reference them in the text.)56 nin
Recall from Chapter 5 that VBA lets you declare variables either implicitly or explicitly. As you'll see shortly, each approach has its pros and cons. However, explicit declarations are almost always the best approach, and when you've been working with VBA for even a little while, you'll probably prefer to be explicit all the time (even if your workplace practices don't insist on it).
It's just best to declare your variables explicitly right from the beginning. I'll now illustrate how to make implicit declarations so you know that technique if that's your preference.
Declaring a variable implicitly means that you just use it in your code without first declaring it explicitly (for example:
).Dim x As Integer
When you declare a variable implicitly, the first time you mention it in your code is when you assign a value to it (x = 12). This implicit value assignment causes VBA to check to make sure that there isn't already an existing variable with that same name. It then automatically creates a variable with that name for you and assigns it the Variant data type, which can contain any type of data except a fixed-length string.
For example, in the previous chapter, you declared the variable
by using the following implicit declaration:myVariable
myVariable = “Sample variable text"
Here,
is implicitly declared as a variable—because it is used in a statement rather than first being declared explicitly (usually with the myVariable
command, which we'll get to shortly).Dim
VBA assigns an implicitly declared variable to the Variant data type, which has a dozen or so subtypes. In the previous example, the variable's subtype is string because you assigned text to it. VBA usually assigns the variable the value
(a special value used to indicate Variant variables that have not yet been used during execution) when it creates it, but in our example the variable receives a value immediately (because the string of text is assigned to it). VBA then assigns the string type because it can see you're storing a string in the variable.Empty
The advantage of declaring a variable implicitly is that you write less code. When you want a variable, you simply declare it on the spot by using it in a statement. But declaring a variable implicitly also has a couple of rather serious disadvantages:
FilesToCreate
and then later type FllesToCreate
instead. VBA doesn't query the latter spelling (with its double ll
typo). No error messages are displayed. VBA merely creates another, new, different variable with the ll
name.
When you're working with many variables, it can be difficult and time-consuming to catch little typo mistakes like this. This kind of mistake (having two variables when you think you have only one) causes errors. The problem in this example is that you think you're referring to the
variable, but you're not. VBA can detect this kind of error, but only if explicit declaration is enforced. (Enforced here means that if you try to get away with using an undeclared variable, the Visual Basic Editor displays an error message and halts execution.)FilesToCreate
What's more important on an underpowered computer is that manipulating Variants takes longer than manipulating the other data types. This is because VBA has to keep checking to see what sort of data is in the variable. Memory and speed are far less significant issues than they used to be, but some special-purpose computers (built into a forklift for instance) can even today be small and slow.
You can get around this second disadvantage in a couple of ways: first, by using a type-declaration character to specify the data type when you declare a variable implicitly or, second (as you will see in the next section), by simply telling VBA to force you to declare variables explicitly—and to display an error message if you don't. However, this technique is rarely employed any more.
A type-declaration character is a character that you add to the end of a variable's name in an implicit declaration to tell VBA which data type to use for the variable. Table 6.1 lists the type-declaration characters.
TABLE 6.1: Type-declaration characters
CHARACTER | DATA TYPE OF VARIABLE | EXAMPLE |
|
Integer | |
|
Long | |
|
Currency | |
|
Single | |
|
Double | |
|
String (variable length) | |
You could implicitly declare the String variable
with the following statement, which assigns the value UserName
to the variable:Jane Magnolia
UserName$ = “Jane Magnolia"
You could implicitly declare the currency variable
by using this statement:Price
Price@ = Cost * Margin
You use the type-declaration character only when declaring the variable. Thereafter, you can refer to the variable by its name—
and UserName
in the previous examples.Price
Declaring a variable explicitly is the best practice. It means telling VBA that the variable exists before you use it. VBA allocates memory space to that variable and registers it. You can also declare the variable type at the same time, which is a good idea, but not obligatory.
You can declare a variable explicitly at any point in code before you use it, but custom and good sense recommend declaring all your variables at the beginning of the procedure that uses them. (Or, to give a variable greater scope (available to all your macros in the module), declare it in the General Declarations area up at the top of the Code window. You'll learn more about scope later.)
Locating all your declarations at the start of a macro's code makes them easy to find, which helps anyone reading the code.
Declaring variables explicitly offers the following advantages:
Option Explicit
statement at the top of a module—in the General Declarations section of the Code window. This enforcement makes it more difficult for you to create new variables unintentionally by mistyping the names of existing variables.The disadvantage of declaring variables explicitly is that doing so takes a little more time, effort, and thought. For most code, however, this minor disadvantage is far outweighed by the advantages.
To declare a variable explicitly, you use one of the following keywords:
, Dim
, Private
, or Public
.Static
For example, the following statement declares the variable
:MyValue
Dim MyValue
is the most common keyword to use for declaring a variable, and you'll probably want to use it for most of your variable declarations. You use the other keywords to specify a different scope, lifetime, or data type for the variable in the declaration. In the previous example, the Dim
variable will have the default scope and lifetime and the Variant data type, which makes it suitable for general-purpose use.MyValue
You can also declare multiple variables on the same line by separating the variable statements with commas:
Dim Supervisor As String, ControllerCode As Long
This can help you keep down the number of declaration lines in your code, but it makes the declarations a little harder to read, so it's not usually a good idea.
Be warned that when you declare multiple variables on the same line, you must specify the data type for each, as in the previous example. You might be tempted to try a little abbreviation, like this, hoping for a couple of String variables:
Dim strManager, strReportingEmployee As String
This statement doesn't create two String variables:
will be a String variable, but strReportingEmployee
will be a Variant because the strManager
part of the code applies only to As String
. And the default, if the type isn't specified, is Variant.strReportingEmployee
The scope of a variable is the area where it can operate. Think of it as similar to your scope of activity at work: those areas in which you perform tasks. Your scope might be limited to the cubicles area of the office. If you were found slinking around inside the walk-in safe, there would be trouble. A variable can have three types of scope:
Entering the safe is not part of your job description. So scope can be visualized as a space. There are three areas of space within which the variable can exist:
The default scope of a variable is the procedure in which that variable is declared. In other words, the scope is the space in the code between the
and Sub
(or End Sub
and Function
). This space is the start and end of a given procedure. Macros are most often fairly short, so their code is most often contained within a single procedure. For the typical macro, there's no reason for a variable to have a scope any larger than its own procedure.End Function
Here's an example of procedure-level scope. Suppose you have two macros called
and Breakeven_Table
. Would there be a problem for VBA if you used a variable named Profit_Analysis_Table
in both of these procedures? No. The variables in each procedure are distinct from the variables in the other procedure, so there is no danger of VBA confusing the two when the macros are executed. Each instance of Expenses
is walled off, its scope limited to its own procedures. It doesn't leak out into other procedures. It's said to be local to its procedure. It's called a local variable.Expenses
If a variable's scope is its space, the lifetime of a variable is the time during which it exists. Lifetime is the period during which VBA can access value of the variable (to put it a different way, the period during which the variable even exists).
You need different lifetimes for your variables for different purposes. Just as Einstein combined space and time into spacetime, a variable's lifetime is relative to its scope.
Variables declared within a procedure have the briefest lifetime: They only exist while that procedure is executing. For most macros, however, this is the usual lifetime because macros are typically self-contained and need not pass data to other macros.
Sometimes you do want to access a variable from outside the procedure in which it's declared, however. In these cases, you declare a different, wider scope for the variable. You can do this by declaring a variable up top in the Editor's Code window, above the first procedure in the module. Such a variable is said to have global rather than local scope. Likewise, a global variable is accessible from the code in any of the procedures within the module—so its lifetime is greater than a local variable.
In practice, though, we're using macros, and they rarely act in concert with other macros, so the need for a global variable to communicate data between them is equally rare. In fact, if you do need to send data from one macro to another, making them functions is preferable. Functions are designed to transmit data outside their own procedure. Because global variables can cause certain kinds of problems—many experts tell you to avoid them if at all possible.
That said, you'll find an example in Listing 6.1 later in this chapter that shows how to use a global variable to communicate a variable's data between two different macros.
Recall that a variable with procedure scope (also known as procedure-level scope or local scope) is available only to the procedure that contains it. As a result, the lifetime of a local variable is limited to the duration of time that its procedure is actively running. As soon as that procedure stops running (the
line of code executes). VBA evaporates all local variables and reclaims the memory that held them for future use. This is true even if later on that same procedure is executed again. Local variables don't persist once execution moves outside their procedure. But again, macros are usually written within only a single procedure, so local variables are usually all you need.End Sub
For example, say you declare a Variant variable named
, like this:Supervisor
Dim Supervisor = “Paul Smith"
You can then use this
variable in the rest of that procedure—for example, retrieving the text stored in it or changing that text. But when the procedure stops running, VBA removes the variable. VBA forgets its name and its value.Supervisor
To explicitly declare a local variable, use the
keyword and place the declaration inside the procedure, like this:Dim
Sub Create_Weekly_Report()
Dim strSupervisor As String
Dim lngController As Long
…
End Sub
Here, the second line declares the variable
as the String data type, and the third line declares the variable strSupervisor
as the Long data type. (The section “Specifying the Data Type for a Variable,” a bit later in this chapter, goes through the variable types.)lngController
On the other hand, if you need to pass any of these variables to another procedure that you call from the current procedure, procedure (local) scope isn't sufficient—you need to use either private scope or public scope.
A variable declared with private scope is available to all the other procedures in the module that contains it (but not to procedures in other modules). Using private variables enables you to pass the value of a variable from one procedure to another, without needing to create a function. Unlike local variables, which retain their value only as long as the procedure that contains them is running, private variables retain their value as long as any procedure in the project that contains them is executing.
To declare a variable with private scope, you can use either the
keyword or the Dim
keyword, but use them up at the beginning of a module, placing it up top before the Private
statement for the first procedure in the module, like this:Sub
Dim strSupervisor As String
Private blnConsultantAssigned As Boolean
Sub Assign_Personnel()
…
End Sub
The Visual Basic Editor displays the private declarations above the dividing line that appears between the General Declarations area and the code below it (see Figure 6.2).
You'll notice that the
statement here uses exactly the same syntax as the earlier declaration for the local variable. The only difference is that here you place the Dim
statement in the declarations area of a module (up top) rather than within a particular procedure. Because the Dim
statement has the same effect as the Private
statement for declaring private variables, and can't be used within a procedure, it's clearer to use the Dim
statement rather than the Private
statement for declaring private variables. (The term private is a bit confusing because they're not private to a procedure, only private to their module.)Dim
A variable declared with public scope is available anywhere in an entire project. It's accessible by all procedures in all modules in the project that contains it.
To declare a public variable, you use the
keyword in the General Declarations area at the beginning of a module (up above the Public
statement for the first procedure in the module). Here's an example:Sub
Option Explicit
Public intMyVar As Integer
The second statement declares the public variable
as the Integer type.intMyVar
Like private variables, public variables retain their value as long as the project that contains them is running. For example, if you want to track the user's name through a series of operations in Word, you can create an
procedure that prompts users to enter their name when they start Word. (AutoExec
is the built-in name for a procedure that runs automatically when Word starts. Word, when you start it, searches to see if there is a AutoExec
named Sub
and, if so, executes that procedure.)AutoExec
By storing the result of the user's input in a public variable, you can retrieve the value for use any time later in the same Word session. You can see how this would be handy if several macros needed the information contained in a variable. Remember that local variables (those declared inside a procedure) are destroyed as soon as that procedure reaches its
statement and shuts down. And Private variables are limited to a single module.End Sub
Listing 6.1 shows an
procedure.AutoExec
This code consists of three different parts: the General Declarations area, followed by two macros:
strCurrentUser
.AutoExec
procedure. This procedure runs each time the user starts Word. Line 4 displays an input box that prompts users to enter their name and stores their response in the public variable strCurrentUser
.Identify_Current_User
procedure, which simply displays a message box that gives the name of the user, along with lead-in text and an information icon and title bar for completeness.You can test these procedures by stepping through (by pressing the F8 key) first the
procedure and then the AutoExec
procedure in the Visual Basic Editor. To see their effect, you'll have to create the procedures and then exit Word. When you restart Word, the Identify_Current_User
procedure displays the input box for you to enter your name. At any point thereafter (until you exit Word), you can access the value in the AutoExec
variable. For example, you could run the strCurrentUser
procedure at any time (until you close Word itself), and VBA displays a message box with the name you entered. A public variable is said to persist, a synonym for remain alive.Identify_Current_User
Besides declaring variables with
, Dim
, and Private
, you can also use the Public
keyword, which is special. You use it to extend the lifetime of a local variable. Use Static
instead of Static
when you want to declare a static variable—a variable whose values you want to preserve between calls to the procedure in which they are declared.Dim
Static variables are similar to public variables in that their lifetime is not limited to the duration of the procedure that declares them. The difference is that static variables, once declared, are available only to the procedure that declared them, whereas public variables are available to all procedures once they've been declared. So, a static variable has the scope of a local variable but the lifetime of a public or private variable. To be practical, there is one particular situation where static variables come in handy: toggling. Think of a light switch. It has two possible states: on or off. But because it's a physical switch, it is always in one of those positions. In other words, its “state” persists. And when you flip it, reversing its state, you can be said to toggle it.
Static variables are useful for maintaining information on a process that you need to run a number of times during a session of the application, either to maintain a running total (for example, a count of the times you performed a procedure) or to keep at hand a piece of information that may prove useful when you run a procedure a second or subsequent time.
Typically, you employ a static variable in a procedure that toggles something between two states. For example, you could create a procedure that when first executed turns on italics, but when next executed turns italics off. Then back on, then off, and so on. In code, such a toggle behavior would look something like this:
Sub ToggleItal()
Static switch As Boolean
switch = Not switch
If switch Then
MsgBox “on"
Else
MsgBox “Off"
End If
End Sub
You can test this as usual by stepping through it (pressing F8 after clicking the first line of the procedure). Each time you execute the procedure, you get a different message.
The
command switches a Boolean variable type back and forth between Not
and True
. A Boolean variable has only those two possible values. Just like a light switch. The False
command in effect flips the switch.Not
Table 6.2 explains the data types that VBA supports and the amount of memory each variable type requires.
TABLE 6.2: VBA variable data types
VARIABLE | SHORT DESCRIPTION | MEMORY REQUIRED |
Boolean | or
|
2 bytes |
Byte | An integer from 0 to 255 | 1 byte |
Currency | A positive or negative number with up to 15 digits to the left of the decimal point and 4 digits to the right of it | 8 bytes |
Date | A floating-point number with the date to the left of the decimal point and the time to the right of it | 8 bytes |
Decimal | An unsigned integer scaled by a power of 10 | 12 bytes |
Double | A floating-point number with a negative value between –1.79769313486231570E+308 and –4.94065645841246544E-324 or a positive value between 4.94065645841246544E-324 and 1.79769313486231570E+308 | 8 bytes |
Integer | An integer from –32,768 to 32,767 | 2 bytes |
Long | An integer from –2,147,483,648 to 2,147,483,647 | 4 bytes |
Object | A reference to an object | 4 bytes |
Single | A floating-point number with a negative value between –3.4028235E+38 and –1.401298E-45 and a positive value between 1.401298E-45 and 3.4028235E+38 | 4 bytes |
Variable-Length String | A string of text | 10 bytes plus the storage for the string |
Fixed-Length String | A string whose length doesn't change | Whatever size is specified for the length |
Variant | Any type of data except a fixed-length string in a subtype of the Variant | Variants containing numbers: 16 bytes; Variants containing characters: 22 bytes plus the storage for the characters |
The next few pages discuss these data types in detail.
Specifying the data type for each variable you create is a good idea, but it's not compulsory. You're permitted to use the default Variant data type (as you've done a couple of times so far in this book's examples) and let VBA figure out which subtype to assign to the Variant.
But remember that even though something is possible, it might not be wise. You can drive with your legs crossed, but it's a bad idea.
There are four disadvantages to using the Variant data type like this:
To sum up, most programming experts frown on the Variant and suggest that it's better to always specify the data types when you declare your variables. So let's now take a closer look at the data types in VBA.
A Boolean variable can be set only to
or True
. You can use the keywords False
and True
to set the value of a Boolean variable, as in the second line in the following code (the first declares the Boolean variable False
):blnProduct_Available
Dim blnProduct_Available As Boolean
blnProduct_Available = True
You can then retrieve the result of the Boolean variable and take action accordingly:
If blnProduct_Available = True Then
MsgBox “The product is available."
Else 'blnProduct_Available = False
MsgBox “The product is not available."
End If
Variables can be converted from one data type to a different one. When you convert a Boolean variable to another data type (such as a numeric value),
returns True
and –1
returns False
. When you convert a numeric value to a Boolean value, 0
returns 0
and all other numbers (whether positive or negative) return False
.True
Boolean variables take up 2 bytes each in memory.
A Byte variable takes up the least memory of any data type—just 1 byte—and can store a number from 0 to 255.
The Currency data type is designed for use with money. It allows for positive and negative numbers with up to 15 digits to the left of the decimal point and 4 digits to the right of it. Unlike the Single and Double data types, the Currency data type is exact, not rounded.
To implicitly declare a Currency variable, use the type-declaration character
. For example, you could work out your weekly salary with a little simple math:@
Sub Calculate_Weekly_Salary()
Salary@ = InputBox("Enter your salary.", _
“Calculate Weekly Salary")
WeeklySalary@ = Salary / 52
MsgBox WeeklySalary
End Sub
The Date data type is relatively complex. VBA works with dates and times as floating-point numbers, with the date displayed to the left of the decimal point and the time to the right. VBA can handle dates from 1 January 100 to 31 December 9999 and times from 0:00:00 to 23:59:59.
You can enter date variables as literal date values—such as 6/30/36 or June 30, 1936—by placing a # sign before and after the literal date value:
#June 30, 1936#
When you move the insertion point from the line in the Code window in which you've entered a literal date value between # signs, VBA converts the data to a number and changes the display to the date format set in your computer. For example, if you enter June 30, 1936, VBA will probably display it as
. Likewise, you can enter a literal time value (for example, #10:15PM#), and VBA converts it to a number and displays it according to the current time format (for example, 6/30/36
10:15:00
).PM
The Decimal data type stores unsigned integers, scaled by powers of 10. Unsigned means that the integers carry no plus or minus designation. Note that you can't declare a Decimal variable directly: You can use the Decimal data type only within a Variant data type (discussed later in this section).
The Double data type is for floating-point numbers and can handle negative values from –1.79769313486231570E+308 to –4.94065645841246544E-324 and positive numbers from 4.94065645841246544E-324 to 1.79769313486231570E+308.
Some numbers in this range cannot be represented exactly in binary, so VBA rounds them.
Double here stands for double-precision floating point—the way in which the number is handled by the computer. Single (discussed later) stands for single-precision floating point.
You can use the
type-declaration character to declare a Double variable implicitly.#
The Integer data type is the most efficient way of handling numbers within its range (from -32,768 to 32,767), a range that makes it useful for many procedures. For example, if you wanted to repeat an action 300 times, you could use an Integer variable for the counter, as in the following lines:
Dim intMyVar As Integer
For intMyVar = 1 to 300
'repeat actions
Next intMyVar
The Integer is the most commonly used numeric data type for many programming tasks. This is because unless you're working with something like moon rockets or the national debt, most math will fall within the Integer type's range.
The Long (integer) data type is for calculating the California state debt. A Long can hold integer values larger or smaller than those the Integer data type can handle: long variables can handle numbers from –2,147,483,648 to 2,147,483,647. (For numbers even larger or smaller than these, use the Double data type, but beware of its rounding problem.)
Long variables use the type-declaration character
for implicit declarations and take up 4 bytes each.&
The Object data type is for storing addresses that reference objects (for example, objects in an application's object model), providing an easy way to refer to an object.
The Single data type, like the Double data type, is for working with floating-point numbers. Single can handle negative values from –3.4028235E+38 through –1.401298E-45 and positive values from 1.401298E-45 through 3.4028235E+38.
Some numbers in this range cannot be represented exactly in binary, so VBA rounds them.
Use the exclamation point type-declaration character to declare a Single variable implicitly (if you must use implicit declarations).
The String data type is for handling text, and it comes in two flavors—variable-length and fixed-length:
If the data assigned to the String variable is shorter than the fixed length, VBA pads the data with trailing spaces to make up the full complement of characters. If the text assigned to a fixed-length String variable is longer than the fixed length, VBA truncates the text, lopping off the necessary characters from the right end of the string.
VBA counts the characters from the left end of the string—for example, if you assign the string
to a fixed-length String variable that's four characters long, VBA stores Output
. Fixed-length String variables are rarely used in most programming, with the exception of managing certain types of database fields, where the number of characters is predictable and invariable. For example, state abbreviations could be stored in a fixed length of two. This approach can be useful because no delimiter is necessary. It's speedy, too.Outp
Dim strStateAbbreviation As String * 2
@
and *
.$
type-declaration character to declare a String variable implicitly, but (as usual) you'll do best to declare your String variables explicitly, along with all your other variables.The Variant data type, as mentioned earlier in this chapter, is the default type. It's assigned by VBA to any variable whose data type isn't specified by you—so a declaration such as
creates a Variant. However, Dim myUntypedVariable
creates a variable of the Integer data type. (You can also declare a Variant variable explicitly: Dim intVariable As Integer
, for example.)Dim myVariant As Variant
Variants can handle most of the different types of data, but there are a couple of characteristics of Variants to keep in mind:
Empty
(which means the variable hasn't yet been initialized), Error
(a special value used for tracking errors in a procedure), Nothing
(a special value used for disassociating a variable from the object it was associated with), and Null
(which you use to indicate that the variable deliberately contains no data).Variant variables take up more memory than other types. Variant variables that contain numbers take up 16 bytes, and Variant variables that contain characters take up 22 bytes plus the storage required for the characters.
If you found the details of the different types of variables confusing, relax. You'll mostly use strings and integers. Here are some straightforward rules to direct your choices:
True
and False
, you can declare it as the Boolean data type.A constant is a named item that keeps a constant value during execution of a program. VBA provides many built-in constants, but you can also declare your own constants to help you work with information that stays constant through a procedure. Recall that many programmers simply use variables rather than constants, even for values that won't change (such as the number of eggs in a dozen). However, constants are available if you or your superiors find them of value.
To declare your own constants, use the
statement. By declaring a constant, you can simplify your code when you need to reuse a set value a number of times in your procedures.Const
The syntax for the
statement is as follows:Const
[Public/Private] Const constant [As type] = expression
Here,
and
Public
are optional keywords used for declaring public or private scope for a constant. You'll learn how they work in a moment.
Private
is the name of the constant, which follows the normal rules for naming variables.
constant
is an optional argument that specifies the data type of the constant.
type
is a literal (a value written into your code), another constant, or a combination of the two.
expression
As with variables, you can declare multiple constants in the same line by separating the statements with a comma:
Const conPerformer As String = “Carmen Singer", _
conTicketPrice As String = “$34.99"
Declaring a constant in VBA works in a similar way to declaring a variable explicitly, but you declare the value of the constant when you declare the constant (rather than at a later point of your choosing). You can't change its value afterward.
As an example, take a look at the following statements:
Const conVenue As String = “Davies Hall"
Const conDate As Date = #December 31, 2019#
MsgBox “The concert is at “ & conVenue & “ on “ _
& conDate & “."
The first line declares the constant
as a String data type and assigns it the data conVenue
. The second line declares the constant Davies Hall
as a Date string type and assigns it the date conDate
. (When you finish creating this line of code and move the insertion point to another line, VBA changes the date to the date format set in your computer's clock—December 31, 2019
, for example.) The third line displays a message box containing a string concatenated from the three text items in double quotation marks, the #12/31/2019#
string constant, and the conVenue
date constant.conDate
Scope works the same way for constants as it does for variables. The default scope for a constant declared in a procedure is local—that is, its scope is the procedure that declares it. Consequently, its lifetime is the time for which the procedure runs. But you can set a different scope and lifetime for your constants by using the
or Public
keyword:Private
Private Const conPerformer As String = “Carmen Singer"
Public Const conTicketPrice As String = “$34.99"
In addition to the constants you can create in your code, VBA includes sets of predefined constants. An enumeration is a predefined list of unique integers (numbers) that have individual names. It's a set of items, related in some way.
Here's an enumeration, a set of items that you need to paint a room. Note that another way to describe this is that it's a numbered list:
You could now refer to any of these items by either their number in the enumeration or by their name.
An enumeration is typically used in your programming to specify a property of an object. Each integer in the enumeration has a meaning to VBA and a name that allows you to refer to it easily. The names that correspond to the integers in the enumeration are called enumerated constants.
For example, when you use the
function to display a message box using VBA, you can pick one of the enumerated constants in the MsgBox
enumeration to specify the type of message box you want to show. If you require an icon in the message box, you can specify which icon from the list of available built-in icons. For example, one of the icons—a stop sign—is the enumerated constant VbMsgBoxStyle
(or the integer vbCritical
). The enumerated constant 16
(integer vbQuestion
) displays a question-mark icon, and the enumerated constant 32
(vbExclamation
) displays an exclamation-point icon. The enumerated constant 48
(vbInformation
) refers to an information icon. However, in practice, the integers are rarely used. The enumerated constants (names like 64
) are far easier for humans to grasp, read, and remember than the values (the various integers like vbQuestion
, 16
, 32
, and so on) to which they are mapped. So, although you could use the integers in your code, it's better to stick with the enumerated constants like 64
.vbQuestion
VBA includes many built-in enumerations, and the Visual Basic Editor displays the list of available enumerated constants to help you select the appropriate integer value when you're creating code. To see such a list, type this into a procedure:
msgbox("inga",
As soon as you type the comma (see Figure 6.3), up pops the list of enumerated constants, all the available button styles for a message box, including
, vbQuestion
, vbYesNo
, and so on. As you might guess, the vbOKOnly
style displays only a single button, captioned OK. The vbOKOnly
style displays two buttons, one captioned Yes, the other No.vbYesNo
You just click one of these button styles in the list of enumerated constants to enter it into your code. If you don't see the list, choose Tools ➢ Options in the Visual Basic Editor, and then select the Auto List Members check box.
You can also define your own enumerations in custom objects that you create.
CustomersAge
.Stop
or End
. There are other restrictions too, such as not using special characters.
Dim 1Turn! as Integer
AnnualSales
that will be available to any procedure within its own module but not to other modules.Dim
command. Name your constant FirstPrez
, and assign it the value George Washington
.ThisDocument
object to select it. Then locate the JustificationMode
property in the Properties window, and choose one of that property's enumerated constants by clicking the small down arrow that appears and then clicking one of the constants in the drop-down list.