Excel 2007 Formulas (Mr. Spreadsheets Bookshelf)

A variable is a named storage location in your computer's memory. Variables can accommodate a wide variety of data types-from simple Boolean values (TRUE or FALSE) to large, double-precision values (see the following section). You assign a value to a variable by using the assignment operator, which is an equal sign.

The following are some examples of assignment statements that use various types of variables. The variable names are to the left of the equal sign. Each statement assigns the value to the right of the equal sign to the variable on the left.

x = 1 InterestRate = 0.075 LoanPayoffAmount = 243089 DataEntered = False x = x + 1 MyNum = YourNum * 1.25 HallOfFamer = "Trevor Hoffman" DateStarted = #3/14/2007#

VBA has many reserved words, which are words that you can't use for variable or procedure names. If you attempt to use one of these words, you get an error message. For example, although the reserved word Next (which is used in a For-Next loop) may make a very descriptive variable name, the following instruction generates a syntax error:

Next = 132

Unfortunately, sometimes syntax error messages aren't descriptive. The preceding instruction generates the error Compile error: Expected: variable in Excel 2007. (Earlier versions of Excel may produce a different error.) So if an assignment statement produces an error that does not seem to make sense, check the Help system to make sure that your variable name does not have a special use in VBA.

Defining Data Types

VBA makes life easy for programmers because it can automatically handle all the details involved in dealing with data. Data type refers to how data is stored in memory-as integers, logical values, strings, and so on.

Although VBA can take care of data typing automatically, it does so at a cost-namely, slower execution and less efficient use of memory. If you want optimal speed for your functions, you need to be familiar with data types. Generally, it's best to use the data type that uses the smallest number of bytes yet still is able to handle all of the data that will be assigned to it. When VBA works with data, execution speed is a function of the number of bytes that VBA has at its disposal. In other words, the fewer bytes used by data, the faster VBA can access and manipulate the data. Table 24-1 lists VBA's assortment of built-in data types.

Table 24-1: VBA DATA TYPES

Open table as spreadsheet

Data Type

Bytes Used

Range of Values

Byte

1 byte

0 to 255

Boolean

2 bytes

TRUE or FALSE

Integer

2 bytes

–32,768 to 32,767

Long

4 bytes

–2,147,483,648 to 2,147,483,647

Single

4 bytes

–3.402823E38 to –1.401298E–45 (for negative values); 1.401298E–45 to 3.402823E38 (for positive values)

Double

8 bytes

–1.79769313486231E308 to –4.94065645841247E–324 (negative values); 4.94065645841247E–324 to 1.79769313486232E308 (positive values)

Currency

8 bytes

–922,337,203,685,477.5808 to 922,337,203,685,477.5807

Decimal

14 bytes

+/–79,228,162,514,264,337,593,543,950,335 with no decimal point; +/–7.9228162514264337593543950335 with 28 places to the right of the decimal

Date

8 bytes

January 1, 0100 to December 31, 9999

Object

4 bytes

Any object reference

String (variable length)

10 bytes + string length

0 to approximately 2 billion

String(fixed length)

Length of string

1 to approximately 65,400

Variant (with numbers)

16 bytes

Any numeric value up to the range of a double data type

Variant (with characters)

22 bytes + string length

0 to approximately 2 billion

Declaring Variables

Before you use a variable in a procedure, you may want to declare it. Declaring a variable tells VBA its name and data type. Declaring variables provides two main benefits:

You declare a variable by using the Dim keyword. For example, the following statement declares a variable named Count to be an integer.

Dim Count As Integer

You also can declare several variables with a single Dim statement. For example

Dim x As Integer, y As Integer, z As Integer Dim First As Long, Last As Double

Caution 

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 integers:

Dim i, j, k As Integer

In the preceding statement, only k is declared to be an integer. To declare all variables as integers, use this statement:

Dim i As Integer, j As Integer, k As Integer

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

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, 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.

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.

Note 

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 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 Integer = 4 Const Rate = .0725, Period = 12 Const CompanyName as String = "Acme Snapholytes"

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:

Public AppName As String = "Budget Tools"

Note 

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

The vbInformation constant has a value of 64, but it's not important that you know that. If you use the Excel macro recorder to record you actions, you'll find many other constants in the recorded code.

Using Strings

Like Excel, VBA can manipulate both numbers and text (strings). VBA supports two types of strings:

Each character in a string takes 1 byte of storage. When you declare a string variable with a Dim statement, you can specify the maximum length if you know it (that is, a fixed-length string), or you can let VBA handle it dynamically (a variable-length string). In some cases, working with fixed-length strings may be slightly more efficient in terms of memory usage.

In the following example, the MyString variable is declared to be a string with a fixed length of 50 characters. YourString is also declared as a string but with an unspecified length.

Dim MyString As String * 50 Dim YourString As String

Using Dates

You can use a string variable to store a date, of course, but then you can't perform date calculations using the variable. Using the Date data type is a better way to work with dates.

A variable defined as a Date uses 8 bytes of storage and can hold dates ranging from January 1, 0100, to December 31, 9999. That's a span of nearly 10,000 years-more than enough for even the most aggressive financial forecast! The Date data type is also useful for storing time-related data. In VBA, you specify dates and times by enclosing them between two pound signs (#).

Note 

The range of dates that VBA can handle is much larger than Excel's own date range, which begins with January 1, 1900. Therefore, be careful that you don't attempt to use a date in a worksheet that lies outside of Excel's acceptable date range.

Here are some examples of declaring variables and constants as Date data types:

Dim Today As Date Dim StartTime As Date Const FirstDay As Date = #1/15/2007# Const Noon = #12:00:00#

Note 

Date variables display dates according to your system's short date format, and times appear according to your system's time format (either 12 or 24 hours). You can modify these system settings by using the Regional Settings option in the Windows Control Panel.

Категории