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
Search our website
We also send out useful tips in a monthly email newsletter ...
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.
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!).
|
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:
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
Worksheets("Votes").Select
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:
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.
Some other pages relevant to the above blogs include:
Kingsmoor House
Railway Street
GLOSSOP
SK13 2AA
Landmark Offices
99 Bishopsgate
LONDON
EC2M 3XD
Holiday Inn
25 Aytoun Street
MANCHESTER
M1 3AE
© Wise Owl Business Solutions Ltd 2023. All Rights Reserved.