Why are variables declared in Normal.dot

D

Dave Neve

Hi

In VBA (Word 2002) , I can now get some simple code to work (sometimes) with
variables.

But I don't understand why variables only work when declared in the macros
belonging to Normal.dot

If I place the same variable in my project, user form, code, it doesn't
work.

Seems weird to me to have to put variables for a specific project in a
general template.

Comments welcomed.

Thanks in advance
 
H

Helmut Weber

Hi Dave,
if you declare variables in the declarations section(!)
of a module as public they should be available
in all modules of all active projects, AFAIK.
Greetings from Bavaria, Germany
Helmut Weber
 
J

Jezebel

Read help and/or do a Google on variable scope in VB/VBA. (in this respect
VB and VBA are very similar). Variables are recognised within the scope of
their declaration, with three possibilities:

1) Private to the Sub or Function in which they are declared.
2) Private to the code module in which they are declared
3) Public to all code modules.

If you have --

Sub XYZ()
Dim MyVar
...
End Sub

MyVar is recognised only within sub XYZ, and its value is lost when you exit
the sub. You could have another 'MyVar' within another sub -- that would be
a different variable: changes to one will not affect the other.

Variables declared with Dim or Private at the top of a module, outside any
Sub or Function, are available to all the code within that module, but not
to any other module.

Variables declared with Global or Public at the top of an ordinary module
(not a class or form) are available to all code in all modules in the
project. Avoid these as much as possible -- they tend to cause bugs.
 

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