VBA Public Variable – Use a Variable in Multiple Modules or Subs

We have already covered an introduction to variables, constants and VBA data types in an introductory tutorial. We are going to cover Public variables in this tutorial. The definition of a Public variable is a variable that any module, Sub Procedure, Function or Class can access and use within a certain workbook.

Declaring a Public Variable in VBA

There are five main keywords that you can use to declare a variable in VBA. These are:

  • The Dim keyword
  • The Static keyword
  • The Global keyword
  • The Public keyword
  • The Private keyword

The Global variable and the Public variable are very similar.

In order to declare a Public variable, you have to place your variable in the Declarations section of your VBA code below the Option Explicit statement, outside of any of your Sub Procedures or Functions and you also have to use the Public keyword. This is shown below:

Declaring a Public Variable

Public MyVariable as Integer

When you declare a variable as a public variable, you are also inferring to the scope of that variable. You determine the scope of a variable by the keyword you use to declare it and where you place it in your code.


<<Return to VBA Examples