560 attributed reviews in the last 3 years
Refreshingly small course sizes
Outstandingly good courseware
Whizzy online classrooms
Wise Owls only (no freelancers)
Almost no cancellations
We have genuine integrity
We invoice after training
Review 30+ years of Wise Owl
View our top 100 clients
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.
Variables have different scope, according to where and how you define them.
The variables we've seen so far have scope limited to the procedure in which they're defined:
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.
The next level of scope is to declare a variable at the top of a module:
'the name of each superhero
Dim HeroName As String
'the rating assigned to them
Private HeroRating As Long
'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.
Sometimes you'll want a variable to be available to all procedures in all modules in a workbook. Here are some examples:
'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.
|Parts of this blog|
25 Aytoun Street