Basics of VBA / Macros Chapter – 3 (Declaring Variables Part-1)

⏱ 2 min readUpdated 21 June 2020

Here we learn how to declare, initialize and display a variable in Excel VBA. To tell that we are using a variable is called declaring a variable. Place a command button on your worksheet and add the code lines below. To execute the code lines, click the command button on the sheet.

  1. Integer

Integer variables are used to store whole numbers.

Code:

Dim x As Integer
x = 6
Range(“A1”).Value = x

The first code line declares a variable with name x of type Integer. We initialize x with value 6. So we write the value of x to cell A1.

 

Result:

Integer Variable in Excel VBA

    2. String

String variables are used to store text.

Code:

Dim book As String
book = “bible”
Range(“A1”).Value = book

The first code line declares a variable with name book of type String. We initialize book with the text bible. Always use apostrophes to initialize String variables. We write the text of the variable book to cell A1.

Result:

String Variable

    3. Double

A variable of type Double is more accurate than a variable of type Integer and can also store numbers after the comma.

Code:

Dim x As Integer
x = 5.5
MsgBox “value is ” & x

But that is not the right value. We initialized the variable with value 5.5 and we get the value 6. What we need is a variable of type Double.

Result:

Not Accurate Enough

Code:

Dim x As Double
x = 5.5
MsgBox “value is ” & x

Long variables have even larger capacity. Always use variables of the right type. As a result, errors are easier to find and your code will run faster.

Result:

Double Variable

    4. Boolean

Use a Boolean variable to hold the value True or False.

Code:

Dim continue As Boolean
continue = True

If continue = True Then MsgBox “Boolean variables are cool”

The first code line declares a variable with name continue of type Boolean. We initialize continue with the value True. We use the Boolean variable to only display a MsgBox if the variable holds the value True.

Result:

Boolean Variable

Please be with us next time, we will b telling important option know as Option Explicit. It can help you to avoid many errors and debugs. this will also help you to find any missing Declaration of Variable.