Variable Declaration
- Last UpdatedJul 18, 2023
- 2 minute read
In VBA, variables are declared (dimensioned) with the dim statement in the following format.
Dim <VariableName> [ As <DataType> ]
Where:
-
Dim is the required Variable declaration statement BASIC keyword
-
<VariableName> represents the required name of the variable being declared (dimensioned)
-
<DataType> represents the optional VBA data type of the variable being declared
In the variable declaration statement:
-
Every placeholder shown inside arrow brackets ( <placeholder>) should be replaced in any actual code with the value of the item that it describes. The arrow brackets and the word they contain should not be included in the statement, and are shown here only for your information.
-
Statements shown between square brackets ( [ ]) are optional. The square brackets should not be included in the statement, and are shown here only for your information.
If no data type is declared, the data type is Variant by default. To declare a variable other than a Variant, the variable declaration needs to be immediately followed by As <datatype> (where <datatype> represents one of the 10 data types), or appended by a type declaration character such as a $, %, &, !, or # for string, integer, long, single, or double data types respectively. For example:
Dim intVar As Integer
Dim dblVar As Double
Dim vntVar ' as variant by default
Dim strName$, Age% ' multiple declarations on one line
Be aware that multiple declarations in the same statement require individual data type assignment if you want them be other than the variant type. In the following example, only the first variable is not a variant. For example:
Dim strName As String, vntAge, vntAddress
The same statement with data type assignment for every variable would look like the following example:
Dim strName As String, intAge As Integer, strAddress As String