In this tutorial we will cover VBA Global Variables.
Variables in VBA can have 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.
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:
Dim someNumber As Integer
someNumber = 5
The result is:
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 Compile 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 Option Explicit statement, and use the Dim keyword:
When we run the second Sub Procedure instead of an error message, we get the following result in cell A1 of the workbook:
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.
Since this variable is a Global level variable, you can also use it in Module2:
When you run this code from Module2, you get the following result: