VBA Global Variable

Written by

Editorial Team

Reviewed by

Steve Rynearson

Last updated on April 3, 2022

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.

Procedure-level Variable

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.

Sub DeclaringAProcedureLevelVariable()

Dim someNumber As Integer
someNumber = 5
MsgBox someNumber

End Sub

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:

Declaring a Variable at Procedure level and then Getting an 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:

Declaring a Module level variable

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



VBA Coding Made Easy

Stop 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! vba save as

Learn More!

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

(No installation required!)

Free Download

Return to VBA Code Examples