In this tutorial we will cover VBA Global Variables.
In VBA, variables can be declared with different scopes. The scope determines where the variable can be used.
Typically, you will see variables declared at the procedure-level within Sub Procedures or Functions. Procedure-level variables must be declared using the Dim keyword within the procedure where they will be used.
This example declares someNumber as an integer variable within the procedure.
Dim someNumber As Integer
someNumber = 5
You can only use this variable within this Sub Procedure. If you call the variable from another Sub Procedure you would get the following Compile Error:
Module Level Variable
A Module-level variable can be used by any Sub Procedure or Function within that 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:
Now the variable someNumber can be used in both sub procedures.
Global Level Variable
A global-level variable can be used anywhere within your code, within Modules, Functions, Sub Procedures and Classes. Global variables are declared 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:
VBA Coding Made EasyStop searching for VBA code online. Learn more about AutoMacro - A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!