Working with Variables and Data
A variable is a name assigned to a bit of computer memory that is used to hold a value. Variables are key features of any programming language, and VBA is no exception. Variables play an important role in all but the most trivial VBA macros.
Using assignment statements
You use an assignment statement to assign values to variables. For example:
Pi = 3.14159 X = 0 MessageText = "This is my first message"
In a concession to the 40-year-old legacy of BASIC programming, in VBA you can preface assignment statements with the keyword Let:
Let Pi = 3.14159 Let x = 0 Let MessageText = "This is my first message"
The Let keyword isn't required, however, and is considered quaint.
Declaring variables
You declare a variable by using a Dim statement, like this:
Dim i As Integer
This statement declares a variable named i. The type of the variable is Integer.
Variable names, which must start with a letter, can be as long as 40 characters and can contain only letters and numerals and the underscore (_). Also, you cannot use any VBA reserved words (such as function names) or names of VBA statements, for example.
You use the As keyword to specify the data type for variables. VBA provides a number of data types you can use for variables:
- Boolean: True or False values.
- Byte: Integers from 0 to 255.
- Integer: Integers from -32,768 to +32,768.
- Long: Large integers. Values can be from approximately -2 billion to +2 billion.
- Currency: Decimal numbers with as many as 19 digits.
- Single: Single-precision, floating-point numbers, not used often in Word macros.
- Double: Double-precision, floating-point numbers, used even less often in Word macros.
- Date: A date or time value.
- String: A bit of text, such as "Twinkle-Twinkle."
- Object: Any object, such as a Word document or a window.
- Variant: A generic number or string.
If you omit the data type, Variant is assumed.
Placing your declarations
The normal place to declare variables is within a procedure before you need to use the variable. Some programmers like to place all variable declarations at the start of the procedure, but that isn't necessary. You can declare a variable at any time up to the first time you use the variable.
You can also declare variables at the module level. Module-level variables are available to all procedures in the module. Place any module-level variables before the first procedure in the module.
In this tutorial:
- Programming with VBA
- Basic Structure of VBA Macros
- Understanding the Basic Elements of VBA
- Working with Variables and Data
- Using static variables
- Using Strings
- Of Objects, Properties, and Methods
- Getting to know the object model
- Using the With statement
- Controlling Your Programs
- The ElseIf structure
- For/Next Loops
- User Input and Output
- User-Defined Procedures and Functions