A Global Variable Over Multiple Modules

J

Jeffrey Grantz

I have a set of macros in multiple modules and would like to set a global
variable to be used by all these modules. If I define a global variable
within a module, all the macros in that module can see it but other modules
can't see it. How can I define a variable that can be used across multiple
modules?
 
G

Greg Maxey

Look up Public statement in VBA help. I suppose the key point is:


Variables declared using the Public statement are available to all
procedures in all modules in all applications unless Option Private
Module is in effect; in which case, the variables are public only
within the project in which they reside.
 
J

Jonathan West

Jeffrey Grantz said:
I have a set of macros in multiple modules and would like to set a global
variable to be used by all these modules. If I define a global variable
within a module, all the macros in that module can see it but other modules
can't see it. How can I define a variable that can be used across multiple
modules?

Define the variable before the first routine in a module (not a class module
or UserForm), using the keyword Public instead of Dim.

But I'll offer a word of caution here. It is possible to royally mess up
your code by the use of global variables, because they introduce linkages
between routines that can be far from obvious. Generally, variables should
be given the narrowest scope possible, and you should pass variables between
routines by means of the parameter list.

Of course, like all good rules, there are exceptions. For instance, if you
make it a rule that a global variable is set in one routine and only ever
read in all the others, you are fairly safe - the global variable then
becomes a sort of pseudo-constant.

Beware also that once you set the value of a global variable, it retains
that value for as long as the template remains loaded, irrespective of
whether macros are still running, or even if you are still editing the same
document. Next time you run some code in the template that uses the
variable, it will still have that last assigned value.


--
Regards
Jonathan West - Word MVP
www.intelligentdocuments.co.uk
Please reply to the newsgroup
Keep your VBA code safe, sign the ClassicVB petition www.classicvb.org
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top