Share this Page URL

Variables > Variables - Pg. 415

Prefix sng dbl cur dtm obj str var Variable Single Double Currency Date Object String Variant Use the Dim keyword (short for "dimension") to declare a variable. Example 18-4 shows two statements you can use to declare integer and string variables. Example 18-4. Declaring a Variable with Dim Dim intVariable As Integer Dim strString As String You can also declare a variable without specifying its data type (Example 18-5). Example 18-5. Declaring a Variable Without a Data Type Dim variable Variables declared in this fashion have a default data type; they're called variants . A variant is a chameleon data type that can mimic any built-in VBA data type. So, one variant might contain an integer, while another contains a string. Variables are also implicitly declared as variants when you assign a value to a variable that you haven't declared with Dim (Example 18-6). Example 18-6. Implicitly Declaring a Variable as a Variant ' intVariable has not been declared intVariable = 10 While variants are flexible, their use is discouraged except when you must store two different data types in the same variable. Your code runs slower when using variants, since variant values need to be interpreted as a specific data type before they can be used. It is best to declare your variables explicitly with Dim . You can get some help from the VBA environment in this regard. Simply include the Option Explicit statement at the top of your VBA code. When this statement is present, the environment pops up an error message if you try to use a variable before declaring it. Working with VBA A VBA Language Primer | 415