How do public variables work

G

Guest

I declare a Variant in the module level code (above the procedures).
Public UName as variant
The value assigned is preserved between procedures but not between modules.
The help says that variables declared this way are available over all
procedures in all modules and in all applications.
How can I get a variable to maintain its (changing) value across modules.
No errors or breaks accured.
 
D

Douglas J. Steele

Is this in a stand-alone module, or in the module associated with a form?

Put it in a stand-alone module if it's currently in a module associated with
a form.
 
G

Guest

I answered my own question when I tried your suggestion as Global can't be
made in a class module. So I tried it in a normal module and it worked fine.
So did the Public. The answer is if you use public in a class module it works
for that module.
Thanks for your help.
 
D

Douglas J. Steele

Being public in a class module exposes the variable as a property of the
class.

Of course, that means you have to declare the instance of the class as
public.

I created a class named cPhoneBook, with one line in it, a declaration of a
public variable:

Public PhoneNumber As String

I then wrote the following code to demonstrate its use:

Dim cTest As cPhoneBook

Sub TestClass()
Set cTest = New cPhoneBook
cTest.PhoneNumber = "123 456-7890"
Call SecondSub
End Sub

Sub SecondSub()
MsgBox "In SecondSub, cTest.PhoneNumber = " & _
cTest.PhoneNumber
End Sub
 

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