×

VBA Global Variable

What is Global Variable?

The Global Variables in VBA refers to the variables declared before the start of any macro. They are defined outside the functions and are used by all the functions or the modules. Global Variables are usually declared by using the “Public” or the “Global” keyword. It can be used within your Classes, Sub Procedures, Modules, Declarations Section, and Functions. 

With a local variable, you need to declare the same variable every time for each new module or different sub-procedure. Hence, every time a new space is allocated for the pre-defined variable. Also, it makes the maintenance task quite cumbersome. The Global variable was introduced to prevent these problems. All you need is to declare the variable only once outside the modules. It is useful for storing "constants" as it maintains the consistency of VBA code. For Example: If in your code, you are declaring multiple functions wherein every function needs some same data. In that case, you can use the Global variable to access the same data.

Once the Global Variable is initialized, and the code is run. The variable’s value is the same across and can be accessed to all the subprocedures and modules. It is always advisable to maintain a specific module to declare Global variables or all the variables in one place. Thus, it would make the debugging of your VBA code easier. You cannot reset the variable easily, but the only way we can reset the Global variable’s value is by pressing the stop button.

Advantages of Global Variable

The advantages of using the Global Variable are as follows:

  1. Globally accessible – The Global Variables are accessible to all the modules or functions in your VBA code.  
  2. Declared only once- All you need is to declare the variable only once outside the modules and can use it anywhere in the VBA code.
  3. Reduces Complexity- It reduces the complexity of writing the large code and may confuse the use of different variables in different modules or subcategories.
  4. Consistent - It is good to use it for declaring the constant variables as it ensures the consistency of your VBA macro.
  5. Easy Maintenance – The Global variables allows easy maintenance for your code.
  6. Easy readability – It reduces the lines of code by declaring the variable once. Thus, making it more accessible for the programmer to read about constants.

Disadvantages of Global Variable

  1. The global variables are declared explicitly. Hence, it makes the debugging of your code harder.
  2. Any module or function in a program can be used to change the value of the global variable. If any changes are made to the Global variable, it will automatically get implemented at all the places wherein it has been used. Thus, degrading the functionality of your VBA code.
  3. The modules are using global variables, the variable is dependent upon the parent module, and if other modules are presented, you have to redesign each one all over each time.

Example 1: Demonstrating an example without using the Global variable.

Step 1: Open the VBA developer tab either by using the shortcut keywords Alt +F11 or click on developer window -> visual basic editor.

Step 2: Visual Basic Editor will open. The next step is to create a module. Right-clicking on the VBA Project-> Click on Insert-> Click on Module.

VBA Global Variable

Step 3: In the VBA Module window, introduce the sub-block following with your macro name.

Code:

Sub GlobalVariables_Sub1()
‘write code here
End Sub 
VBA Global Variable

Step 4: The next step is to declare a variable within the sub-block with the help of the DIM keyword. Here, we have declared a variable x as String.

Code:

Sub GlobalVariables_Sub1 ()
‘declare your variable x with a string data type.
Dim x As String
End Sub 
VBA Global Variable

Step 5: Initialize the ‘x’ variable. Now, we will declare another sub-block in the same module and introduce another variable ‘y’ with String data type.

Code:

Sub GlobalVariables_Sub1()
'declare your variable x with string data type
Dim x As String
‘initializing x with 10
x=10
End Sub
Sub GlobalVariables_Sub2()
'declare your variable y with string data type
Dim y As String
End Sub 
VBA Global Variable

Step 6: Now, if we will access variable ‘x’ within the Sub GlobalVariables_Sub2() block, you will notice that the program will run without any error displaying ‘x’ as null. It is because in the Sub2() block another x variable is declared by default and has been allocated new storage space.

Note: As represented above, both variables x and y can only be used in their respective subcategories, and if it is defined in another sub-block, either it will throw an error, or the variable will be automatically declared. Thus, creating another space for the same variable. Hence, to make it work, the ‘Option Explicit’ was introduced. The variables declared under this can be used in different sub-blocks within the same module.

Option Explicit

Step 6: We will define the ‘Option Explicit’ keyword at the beginning of the module. And under that will declare another variable Z as String using Dim scope.

Code:

Option Explicit
'declaring variable z with String Data type.
Dim z As String
Sub GlobalVariables_Sub1()
'write your code
End Sub
Sub GlobalVariables_Sub2()
'write your code
End Sub 
VBA Global Variable

Step 7: You can call variable z within any subcategories. Here, we have initialized variables' value of z in both the sub-blocks and, with the help of MsgBox, have displayed the output.

Code:

Option Explicit
'declaring variable z with String Data type.
Dim z As String
Sub GlobalVariables_Sub1()
'initializng the z variable with value 10
z = 10
End Sub
Sub GlobalVariables_Sub2()
'displaying the output of z in this procedure
MsgBox z
End Sub 
VBA Global Variable

Output

Step 8: Execute the above code either by pressing the F5 shortcut key or by clicking on the Run button. You must run the code twice for different subcategories. Firstly, run the code for Sub GlobalVariables_Sub1() block to initialize the Global Variable. Then again, run the code for the second sub procedure to display the output.

VBA Global Variable

Example 2- Within different sub-blocks / Modules

  1. Sub Blocks

Code:

Option Explicit
'declaring the global variable z with as String
'with the help of Global keyword
Global glb As String
Sub GlobalVariables_Sub1()
'initializng the z variable with value 10
glb = 10
End Sub
Sub GlobalVariables_Sub2()
'now, the ‘z’ variable is public and can be used with different sub-blocks
'displaying the output of the z variable
MsgBox glb
End Sub 

Step 1: Open the VBA developer tab either by using the shortcut keywords Alt +F11 or click on developer window -> visual basic editor.

Step 2: Visual Basic Editor will open. The next step is to create a module. Right-clicking on the VBA Project-> Click on Insert-> Click on Module.

VBA Global Variable

Step 3: In the Declarations Section, under the ‘Option Explicit’ command, declare your global variable with Global (you can also use public) keyword.  

Note: You can only declare the variable under the Option Explicit. But it cannot be used to initialize the variable else it will throw a compile error stating “Invalid Outside Procedure”.

VBA Global Variable

Step 4: Introduce a sub-block, and withing that block, we will initialize the global variable ‘glb’ with a value of 10.

VBA Global Variable

Step 5: Introduce another sub-block, within this block, we will display the value for the Global variable ‘glb’ with the help of MsgBox. The Global variable is accessible to all the subcategories. It can be initialized at any sub-block and can be used in another.

VBA Global Variable

Output

Step 6: Execute the above code either by pressing the F5 shortcut key or by clicking on the Run button.

Step 7: Firstly, to the value in variable z, we will run the Sub GlobalVariable_Sub1(). After that, we will run the code for Sub GlobalVariable_Sub2() block. It will give the following output.

VBA Global Variable
  • Modules

Step 8: Within the same VBA Project, introduce another module.

VBA Global Variable

Step 9: In the VBA Module window, within the sub-block, introduce your macro name. And we will only fetch and display the global variable declared and initialized at Module 1.

Code:

Sub GlobalVariable_Module2()
'Fetching and displaying the global variable at Module 2
MsgBox glb
End Sub 

Output

Step 10: Execute the above code either by pressing the F5 shortcut key or by clicking on the Run button.

VBA Global Variable

Hence, it proves that all the subprocedures and modules accept the Global variable with a VBA project editor.


Related Topics

Excel VBA ABS Function

VBA ABS Function: The ABS function in VBA returns the absolute value of the specified number. Syntax Abs (Number) Parameter Number (required) – This parameter represents the number that you want the absolute value of. Return This...

1 minute read.

VBA Charts Basic Operations

VBA Charts- Basic Operations The Chart Object in Excel VBA represents the collection of all the charts sheet present in a workbook. A chart can be either an embedded chart or a separate chart sheet. The...

6 minutes read.

Excel VBA FormatDateTime Function

VBA FormatDateTime Function: The FormatDateTime function in VBA returns the result as a string after applying a date and/or time format to the supplied expression. Syntax FormatDateTime (Expression, [NamedFormat]) Parameter Expression (specified) – This parameter...

2 minutes read.

Excel VBA MonthName Function

Excel VBA MonthName Function: The MonthName function in VBA returns a string with the month name for the specified month number. Syntax MonthName (Month, [Abbreviate]) Parameter Month (required) – This parameter represents an integer between...

1 minute read.

Excel VBA TimeValue Function

Excel VBA TimeValue Function: The TimeValue function in VBA returns a Time from the specified String interpretation of a time /date where the date information for the given string is...

1 minute read.

Excel VBA Exp Function

VBA Exp Function: The Exp function in VBA returns the value of the exponential function ex (mathematical constant ‘e’ raised to specified power) for the given value of x. Syntax Exp (Number) Parameter Number (required) –This parameter represents...

1 minute read.

Excel VBA Fix Function

VBA Fix Function: The Fix function in VBA truncates the given number to an integer and returns the rounded off integer number. This function both positive and negative numbers to zero. Syntax Fix...

1 minute read.

Basics of Userform

A User Form is a built-in customized dialog box that fetches data from the user through a user-friendly dialog box or window that makes up part of an application's user interface. It...

9 minutes read.

Excel VBA DateDiff Function

The DateDiff function in VBA returns a Long data value representing the number of intervals between two specified dates/times where the type of interval is supplied by the user. Syntax DateDiff (Interval, Date1, Date2, [FirstDayOfWeek], [FirstWeekOfYear]) Parameter Interval (required)...

2 minutes read.

Excel VBA CStr Function

VBA CStr Function: The CStr function in VBA converts an expression into a string data type. Syntax CStr (Expression) Parameter Expression (required) – This parameter represents the expression that you want to convert to a...

1 minute read.

Excel VBA Val Function

VBA Val Function: The Val function in VBA converts the given string into a numeric value. This function ignores spaces and continues to read the characters after space(s). It stops...

1 minute read.

Four VBA Clear methods

Four VBA Clear methods In Microsoft Excel, many times, a situation arises where the user wants to clear the data or any specific range of data. What if the user automates this task with...

6 minutes read.

VBA Screen Updating

What is VBA Screen Updating property? Screen Updating is a VBA property which is used to display the output generation while running the code. If this property is enabled, we could see...

6 minutes read.

Excel VBA Space Function

VBA Space Function: The Space function in VBA creates a String consisting of a specified number of spaces. Syntax Space (Number) Parameter Number (required) - This parameter represents the number of spaces. Return This function returns a...

1 minute read.

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...

2 minutes read.

VBA Find Function

VBA Find Function The Excel VBA FIND function finds any information in your Excel. It can be used on a Range object on the worksheet. It works the same, unlike the Excel Find &...

6 minutes read.

VBA UBound

VBA UBound  The UBound or Upper Bound function in VBA is used to specify the length of an array and returns the highest subscript for a dimension for the specified array. It is...

3 minutes read.

Excel VBA Join Function

Excel VBA Join Function: The Join function in VBA is used to join an array of substrings and return them all as a single string. Syntax Join (SourceArray, [Delimiter]) Parameter SourceArray (required) – This parameter...

1 minute read.

Excel VBA Error Handling

What is Errors and Types of Error? Errors are conditions that resist the flow of the program or enables a problem while running any programming. There are three types of errors in VBA...

5 minutes read.

Excel VBA IsArray Function

VBA IsArray Function: The IsArray function in VBA returns a Boolean, showing whether the given variable is an Array or not. Syntax IsArray (VarName) Parameter VarName (required)- This parameter represents the variable that you want...

1 minute read.