VBA Global Variable

We are going to cover Global Variables, in this tutorial. A variable in VBA can have a different scope. A variable’s scope is based on its position in the code and the way it’s declared. The scope of a variable indicates its visibility and where it can be used.

Procedure-level Variable

These variables can only be used within the Sub Procedure or Function that they are declared in. You must declare a Procedure-level variable using the Dim keyword. Additionally, you must place it within the Sub Procedure or Function of interest. The way you would declare a Procedure-level variable is shown in the code below:

Sub DeclaringAProcedureLevelVariable()

Dim someNumber As Integer
someNumber = 5
MsgBox someNumber

End Sub

The result is:

Procure Level Variable in VBA

You can only use this variable within the Sub Procedure called DeclaringAProcedureLevelVariable(). Since it’s in this Sub Procedure and we used the Dim keyword. If you call it from another Sub Procedure you would get the following error:

Declaring a Variable at Procedure level and then Getting an Error

Module Level Variable

You can use a Module level variable in any of the Sub Procedures or Functions within the same module.  You need to place the variable declaration at the top of the module in the Declarations section, under the Options Explicit statement, and use the Dim keyword:

Declaring a Module level variable

When we run the second Sub Procedure instead of an error message, we get the following result in cell A1 of the workbook:
Using a Module Level Variable in VBA

Global Level Variable

You can utilize a Global variable in your Modules, Functions, Sub Procedures and Classes. You declare a Global variable, in the Declarations Section, under the Options Explicit statement and using the keyword Global. The way you declare a Global level variable is shown below. Both of the Sub Procedures in Module1 can use this variable.Declaring a Global Level Variable

Since this variable is a Global level variable, you can also use it in Module2:

Using a Global Variable in Another Module

When you run this code from Module2, you get the following result:Using a Global Variable In Another Module

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

(No installation required!)