×

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

VBA Type Mismatch Error

What is a Type Mismatch Error? VBA Type Mismatch Error is a run time error in excel, which often occurs when the data types contained in a VBA code are not matched...

3 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 IsMissing Function

VBA IsMissing Function: The IsMissing function in VBA checks if any parameter to a procedure is missing or not. It returns a Boolean value True if the specified parameter has not been...

1 minute read.

Excel VBA: IF THEN Statement

VBA Excel: IF THEN StatementThis conditional statement enables you to check one condition and on the basis of that then run one or multiple statements if the condition holds. If...

1 minute read.

Excel VBA Sqr Function

VBA Sqr Function: The Sqr function in VBA returns the square root for the specified number. Syntax Sqr (Number) Parameter Number (required) – This parameter represents a positive numeric value that you want to calculate...

1 minute read.

VBA runtime error 1004

What is 1004 error?  VBA 1004 Error, also known as object-defined or application-defined, is a runtime error in VBA, usually, if the specified range does not exist in the worksheet or if the Application...

6 minutes read.

Excel VBA LBound Function

Excel VBA LBound Function: The LBound function in VBA returns the lowest subscript for the specified dimension in the given array. Syntax LBound (ArrayName, [Dimension]) Parameter ArrayName (required) – This parameter represents an array for which...

1 minute read.

VBA Pivot Table

What is a Pivot Table? One of the most powerful features of Excel VBA is the Pivot Table. A pivot table is a VBA tool that is used to create summary...

3 minutes read.

CodeIgniter File Uploading Class

The Codeigniter provides a file Uploading library class which is used to upload any file such as images, pdf, mp3, etc. to the codeigniter’s application. It also allows to set various preferences such...

5 minutes read.

Excel VBA For Each Loop

A For Each loop executes a statement or a group of statements for each element in an array or collection. It repeats the statement/condition/code for each element in a collection. For Each Loops loop through every...

4 minutes read.

VBA ActiveCell Property

What is the ActiveCell Property? The active cell signifies the active selected cell in the current worksheet. The Active property acts as a reference point and is used to move the cell cursor...

5 minutes read.

VBA Not Equal Operator

What is VBA Not Equal Operator? VBA Not Equal binary operator (“<>”) is a logical function that is used to check if the specified values are not equal or not. This...

5 minutes read.

Excel VBA CDate Function

VBA CDate Function: The CDate function in VBA converts an expression into a Date (or Time) data type. Syntax CDate (Expression) Parameter Expression (required) - This parameter represents the expression that that you want to...

1 minute read.

VBA Creating, Displaying, Uploading UserForms

UserForm is a customized interface and acts as a VBA container and can add various controls as per the required functionality, each of which has certain usage and related properties. You can...

4 minutes read.

Excel VBA IsEmpty Function

VBA IsEmpty Function: The IsEmpty function in VBA returns a Boolean value showing whether the specified Expression is Empty (variant has not been declared) or not. Syntax IsEmpty (Expression) Parameter Expression (required)- This parameter...

1 minute read.

Excel VBA Trim Function

The Trim function in VBA removes the leading and trailing spaces from the specified string. Syntax Trim (String) Parameter String (required) – This parameter represents the string from which you want to remove the leading and...

1 minute read.

Excel VBA Time Function

Excel VBA Time Function: The Time function in VBA returns the current time. Syntax Time () Parameter NA Return This function returns the current time.  Example 1 Sub TimeFunction_Example1() ' returns the current time Dim time_val...

1 minute read.

Excel VBA Choose Function

VBA Choose Function: The Choose function in VBA chooses function selects the corresponding value from a list of arguments depending as per the specified index. Syntax Choose (Index, [Choice-1], [Choice-2], ...) Parameter Index (required) – This...

2 minutes read.

Excel VBA: IF…..THEN …ELSE Statement

VBA : IF…..THEN …ELSE Statement: This function enables you to check one condition and, based on that, then run one of the two statement blocks present. If the ‘IF’ condition...

2 minutes read.

Excel VBA FormatPercent Function

VBA FormatPercent Function: The FormatPercent function in VBA is used to apply a percent format to a numeric expression, and it returns the result as a string. Syntax FormatPercent (Expression, [NumDigitsAfterDecimal], [IncludeLeadingDigit], [UseParensForNegativeNumbers], [GroupDigits]) Parameter Expression (required)...

2 minutes read.