Link to home
Start Free TrialLog in
Avatar of eszSEARCA
eszSEARCA

asked on

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?
ASKER CERTIFIED SOLUTION
Avatar of vindevogel
vindevogel

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.
Avatar of Microsoft
Microsoft

variables explernation


public
option explicit
public myvar as string

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

label1=form1.myvar

private
dim myvar as string

label1=myvar
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
Small correction. You can have 2 public variables (or functions) of the same name in different .bas modules.
Sample:
' 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
Avatar of eszSEARCA

ASKER

Thanks for the simple encouraging answer
You're welcome.  Thanks for the points.