Declare Global Variable (Public) in VBA

HomeVBA TutorialDeclare Global Variable (Public) in VBA

In VBA, when you declare a variable as a global variable you can use it in any procedure in any module. As the name suggests you can use it globally means its availability is everywhere.

So if you have a global variable in the “module1” and now you want to use it in the module2, you can use it.

Declare a Global Variable in VBA

  1. First, you need to use the keyword “Global”
  2. After that, declare the name of the variable.
  3. Next, type “as” to get the list of data types.
  4. In the end, select the data type that you want to declare for the variable.
global-variable-in-vba

Notes

  1. When you are declaring a global variable, you need to declare it before writing any procedure into the module as you can see in the above example.
  2. You can also use the keyword “Public” to declare a variable as global.

Understand Scope of Variables

But to have a clear understanding of a global variable you need to understand the scope of the variables. There are three ways of defining scopes to variables:

  1. Procedure-Level: You can only use a variable in the same procedure where you declare it.
  2. Module-Level (Private): Makes a variable accessible from all the procedures in a module.
  3. Global Level (Public): Makes a variable accessible from all the procedures in all the modules.

Let me share something from the real world with you to make you understand this. I work from a co-working space and the place where I sit is on the first floor in the three-floor building and I mostly sit on the same seat every day.

When you declare a variable with the procedure-level scope you can only use it in the same procedure.

Just like I sit on the same seat on the same floor every day. But let me tell you more: Even though I sit on the first floor, I can use any seat on other floors too.

And in the below snapshot, we have declared the variable “iCon” at the top of the module using the keyword Private before starting any procedure and I have used it in all three codes.

declared-the-variable-icon

Think of this module as a building where you have different floors (Procedures) and as you have already declared the variable at the starting of the module you can use any of the procedures in that module. It is called private module-level scope.

Now here is the last thing: My office has branches in different cities all over the country and if I go there, I can go to those offices and use any of the seats if I want. So, if you have different modules in your workbook, you can use a variable in all those modules by declaring it as Public/Global.

There’s More

If you are preparing for an interview, make sure to check out these VBA interview questions.