Читать книгу Excel 2019 Power Programming with VBA - Michael Alexander, Dick Kusleika - Страница 142

Variables, Data Types, and Constants

Оглавление

VBA's main purpose is to manipulate data. Some data resides in objects, such as worksheet ranges. Other data is stored in variables that you create.

You can think of a variable as 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 equal sign operator (more about this process in the upcoming section “Assignment Statements”).

You make your life easier if you get into the habit of making your variable names as descriptive as possible. VBA does, however, have a few rules regarding variable names.

 You can use alphabetic characters, numbers, and some punctuation characters, but the first character must be alphabetic.

 VBA doesn't distinguish between case. To make variable names more readable, programmers often use mixed case (for example, InterestRate rather than interestrate).

 You can't use spaces or periods. To make variable names more readable, programmers often use the underscore character (Interest_Rate).

 You can't embed special type declaration characters (#, $, %, &, or !) in a variable name.

 Variable names can be as long as 254 characters—but using such long variable names isn't recommended.

The following list contains some examples of assignment expressions 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.87 DataEntered = False x = x + 1 MyNum = YourNum * 1.25 UserName = "Bob Johnson" DateStarted = #12/14/2012#

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 might make a very descriptive variable name, the following instruction generates a syntax error:

Next = 132

Unfortunately, syntax error messages aren't always descriptive. If the Auto Syntax Check option is turned on, you get the error Compile error: Expected: variable. If Auto Syntax Check is turned off, attempting to execute this statement results in Compile error: Syntax error. It would be more helpful if the error message were something like Reserved word used as a variable. So, if an instruction produces a strange error message, check the VBA Help system to ensure that your variable name doesn't have a special use in VBA.

Excel 2019 Power Programming with VBA

Подняться наверх