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

Associated Files Download Links

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

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.

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!

alt text

 

Learn More!


<<Return to VBA Examples

Did you find this VBA tutorial useful? Then share it with your friends and colleagues:

You may also like some of this related content...

We covered arrays, static arrays and dynamic arrays in a previous tutorial.  We are going
A VBA Static variable retains its value even when the procedure ends. Declaring a Static
We covered an introduction to variables and constants in our VBA Data Types – Variables and
We are going to cover Global Variables, in this tutorial. A variable in VBA can
We have already gone over what variables and constants are, in our VBA Data Types
Advertisements
Automate Excel
Left Menu Icon