Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Newbie problem: sharing variables between subs

Status
Not open for further replies.

richey208

Programmer
Jun 29, 2001
1
GB
Hey
In Qbasic I simply declared a variable "dim shared whatever as whatever", so I could access it's value from another sub or function.

Simply, how do I do this in Visual Basic??

When I copy and paste the above code from QB, the "shared" simply disappears and I can't access the array's values from a different sub.

Sorry to be thick but please help! :)

Richey
 
declare your variable like the following at the top of your module:

Public <Name> As <Type>

Rob Marriott
rob@career-connections.net
 
There are a few of ways to do this:

'This will make MyVariable available throughout the form it's declared in, plus any other object that refers to it(Form1.MyVariable = 5)
Public MyVariable as Integer

'this is the same, but it's not accessable from other forms or modules in the project:
Private MyVariable as Integer

'use this one if you only want the variable to exist during the scope of Command1_Click routine:
Command1_Click()
Dim MyVariable as Integer
End Sub

If you do the above (Dim), it uses the least amount of memory(which is good), but if you want any other routine to use it, you have to pass it as an argument(or parameter) like this:

Private Function Double(MyVariable as Integer) as Integer
Double = MyVariable * 2
End Function

Then to call that function, do this:

Dim MyVariable as Integer
Dim Answer as Integer

MyVariable = 5
'Call here:
Answer = Double(MyVariable)


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top