Multiple forms accessing similar variables

I have declared the same variable on several forms. Will the variable on one open form be affected by variables of the same name and type on another open form? How do I avoid this?
Who is Participating?
vindevogelConnect With a Mentor Commented:
No, no problem at all ....
The only problem can occur when you declare them global in a module.

Even if you declare them public on a form, they will not be accessible without giving the form too (like Form1.Variable)
In short form, no  - you need to refer to them in another form as formVariableOwener.VariableName to do this

If declared at form level then declare them

private MyVar as string

..they can not be referenced by another form

if you declare them as

public MyVar

then they can be referenced from another form e.g

form2.MyVar = "x"

You can't have 2 public variables of the same name in different .bas modules, but you can if they are declared in a form of if they are declared as private private.

If you are talking about variables in sub or function.. then they are only used/changed in the function, and you can repeat the variable name between functions.
variables explernation

option explicit
public myvar as string

this will only let you call back the value by :-


dim myvar as string

these 2 examples would not affect each other they will both store information seperate from each other

public vars become form properties

private become form vars only.

hope this helps
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Small correction. You can have 2 public variables (or functions) of the same name in different .bas modules.
' in Form1
Private Sub Form_Click()
    Module1.var1 = 5
    Module2.var1 = 2
    MsgBox Module1.var1
    MsgBox Module2.var1
End Sub

' in module1 and in module2
Public var1 As Integer
eszSEARCAAuthor Commented:
Thanks for the simple encouraging answer
You're welcome.  Thanks for the points.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.