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:
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.
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!
Did you find this VBA tutorial useful? Then share it with your friends and colleagues: