VBA Global Variable

Associated Files Download Links

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:

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

You may also like some of this related content...

We covered arrays, static arrays and dynamic arrays in a previous tutorial.  We are going
A VBA Static variable retains its value even when the procedure ends. Declaring a Static
We covered an introduction to variables and constants in our VBA Data Types – Variables and
We have already covered an introduction to variables, constants and VBA data types in an
We have already gone over what variables and constants are, in our VBA Data Types
Ads