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

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

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

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