Declaring a Variable in VBA

Declaring a Variable

A variable is broadly described as a storage location combined with a name and representing a specific value. Declaring a variable is instructing the computer to reserve space in memory for later use.

Syntax for Declaring Variable

Scope VariableName As DataType

Steps for Declaring Variables 

In VBA, declaring has three steps:

  1. Set a Scope for the variable - Every variable has a scope associated with it. The scope of a variable is defined at the time the variable is declared. The available scope for a variable can be the either of three scopes i.e., Dim, Private, and Public.

2. Set a name for the variable – Variables are allocated with a name so as the can identify the variables for future use. Two variables within the same procedure can not have identical names. There are few naming convictions which are as follows:

  • The first character should be alphabetic.
  • The following characters can be alphabetic, numeric or punctuation character excluding * . , # $ % & !
  • Spaces or periods abandoned.
  • Underscore character is also used to increase readability and distinguish two words
  • The name can have a maximum of 254 characters.
  • Variable names cannot be similar to VBA keywords, unlike Sub, Function, Integer, Array, etc.,.

3. Set a type for the variable – Data Types defines the type of data you’re going to store in the variable. The various data types available are Boolean, Byte, Integer, Long, Currency, Single, Double, Date, String, Object, and Variant.

Program 1

Sub DeclaringVariableExample()
                ‘Declaring the variable ‘a’ with scope= Dim and data type = Integer
Dim a As Integer
a = 12
MsgBox "The value of first variable is " & a
'MsgBox will return the Output: 2
‘Declaring the variable ‘b’ with scope= Dim and data type = Long
Dim b As Long
b = a + 2
MsgBox "The value of second variable is " & b
'Outputs: 4
‘Declaring the variable ‘c’ with scope= Dim and data type = String
Dim c As String
c = "Hello World"
MsgBox "The value of third variable is " & c
'Outputs: Hello, world!
End Sub

Output

The Value of a is 2

Declaring a Variable in VBA

The value of b is 4

Declaring a Variable in VBA

The value of c is Hello, world!

Declaring a Variable in VBA

Declaring Multiple Variables

Program 2

Sub DeclaringMultipleVariableExample()
'declaring multiple variables
Dim X As Integer, Y As Integer, Z As Integer
X = 2
MsgBox "The value of first variable X is " & X
'Outputs: 2
Dim b As Long
Y = X + 2
MsgBox "The value of second variable Y is " & Y
'Outputs: 4
Dim c As String
Z = Y + 2
MsgBox "The value of third variable Z is " & Z
'Outputs: 6
End Sub

Output

The value of X is 2

Declaring a Variable in VBA

The value of Y is 4

Declaring a Variable in VBA

The value of Z is 6

Declaring a Variable in VBA