How to define a variable in one Sub which can be used by another SUb

rickyfong

Registered User.
Local time
Today, 05:26
Joined
Nov 25, 2010
Messages
199
How can I define a variable which can be used by another Sub and of course the value stored in it?? Thanks!!

For instance:

Private SUB A ()
DIM A1 as String
A1 ="ABC"
END SUB

PRIVATE SUB B()
PRINT A1
END SUB
 
You pass it to the second sub as a parameter . . .

So consider the following code . . .
Code:
Sub A
   Dim a1 As String
   a1 ="ABC"
End Sub

Sub B(aParam As String)
   Debug.Print aParam
End Sub
See what's happening there?
 
Then declare the variable at the module level.

From the Help file:
Variables declared with Dim at the module level are available to all procedures within the module.
 
Re: You pass it to the second sub as a parameter . . .

So consider the following code . . .
Code:
Sub A
   Dim a1 As String
   a1 ="ABC"
End Sub
 
Sub B(aParam As String)
   Debug.Print aParam
End Sub
See what's happening there?


1) What's aParam??
2) It seems no linkage between SUb A and B!!

THANKS!!
 
Re: You pass it to the second sub as a parameter . . .

1) What's aParam??
aParam is just a variable.
2) It seems no linkage between SUb A and B!!
I am sure it is a small mistake, the code should have been,
Code:
Sub A
   Dim a1 As String
   a1 ="ABC"
   [COLOR=Red][B]B a1[/B][/COLOR]    [COLOR=Green]'This is where you pass the String A1 in Sub A to Sub B[/COLOR]
End Sub

Sub B(aParam As String)
   Debug.Print aParam
End Sub
JHB's suggestion is an alternative.
 
Yes, I omitted a very important line of code, and pr2-eugin has corrected it, thank you.

Global variables are easy to use, but they are vulnerable, since between the time that you set a global variable, and the time that you use it, other processes have access to it. It's also difficult to document what a global variable is for, and when it contains a legit value.

A computing principle is to always minimize the scope, which is the visibility and accessibility, of your variables. Don't expose a variable any more than is necessary.
 

Users who are viewing this thread

Back
Top Bottom