Variables and Constants in Excel Visual Basic
Part seven of an eight-part series of blogs

This blog explains the nuts and bolts of Excel VBA variables, including how to declare them, how to set their scope and all sorts of other tips and tricks. The blog also covers constants in Excel macros.

  1. Variables in Excel Visual Basic macros
  2. What is a Variable? VBA macro variables.
  3. Declaring Variables in Visual Basic for Applications
  4. Using Variables (Assigning and Retrieving Values)
  5. Forcing Declaration of Variables (Option Explicit)
  6. Useful Things to Know about Variables
  7. The Scope of Variables (this blog)
  8. Constants in Excel Visual Basic for Applications

This blog is part of our Excel macros online tutorial series.  Alternatively, we run training courses in the UK in Excel and also in Visual Basic for Applications (and are always looking for partners in the US or other English-language countries!).

Posted by Andy Brown on 05 September 2011

You need a minimum screen resolution of about 700 pixels width to see our blogs. This is because they contain diagrams and tables which would not be viewable easily on a mobile phone or small laptop. Please use a larger tablet, notebook or desktop computer, or change your screen resolution settings.

The Scope of Variables

Variables have different scope, according to where and how you define them.

Local Scope

The variables we've seen so far have scope limited to the procedure in which they're defined:

Example of local variable

In the top subroutine called SomethingElse, any attempt to reference HeroName will fail, since it is defined within the separate procedure RecordVote and hence is local to that.


Most variables that you create will be locally defined within a single subroutine like this.

Public Scope for a Module

The next level of scope is to declare a variable at the top of a module:

Option Explicit

'the name of each superhero

Dim HeroName As String

'the rating assigned to them

Private HeroRating As Long

Sub RecordVote()

'go to the votes sheet and get the value of the superhero, and their rating


In the code above, HeroName and HeroRating are defined across all procedures within this module.

Dim and Private mean the same thing in the above context.

Highest Scope - Public to All Modules

Sometimes you'll want a variable to be available to all procedures in all modules in a workbook.  Here are some examples:

Option Explicit

'examples of public variables

Public ModelName As String

Public CompanyName As String

Global FilePath As String

Note that the word Global is old-fashioned, but is still supported - you should use Public instead by preference.

If you're using public variables, you may instead want to create them as constants instead - the subject of the last part of this blog.

This blog has 0 threads Add post