Passing variable back up to Main Sub

E

ExcelMonkey

I have passsed variables to subs before, but I do not know how to pas
variables declared in private subs back up to the main sub that calle
it. This is a variable scope question.

I have a main sub which calls two other private subs within it
routine. I need to find a way to make sure that the two private sub
share the same variable and value.

Upon calling the first private sub I declare a variable "X" (withi
this private sub) and pass a value to it "1". I need to pass thi
variable"X" back up to the main sub so that it can be passed to th
second private sub when it is called? So when the second sub i
called, it has access to the "X" and it knows its value ("1") is what
deemed it to be in the first sub. How do I do this?

I am assuming another way around this would be to declare the variabl
before any of the subs so that it is available for all of teh subs.

Thank-yo
 
T

Tom Ogilvy

Sub Main()
Dim mainX as Variant
mainX = 1000
msgbox "mainX: " & mainX
sub1 mainX
msgbox "mainX: " & mainX
sub2 mainX
msgbox "mainX: " & mainX
End Sub

Sub Sub1(X as Variant)
X = 1
End Sub

Sub Sub2(Sub2X as Variant)
Sub2X = Sub2X + 1
End Sub


or a slight variation

Sub Sub1(X as Variant)
Dim Y as Variant
Y = X
Y = 1
X = Y
End Sub
 
B

Bob Phillips

How about using Functions. Return a value from the first, and pass that as
an argument to the second.

Sub Main()
Dim myVar As Long

myVar = myFunc1
myFunc2 myVar

End Sub

Function myFunc1() As Long
myFunc1 = 17
End Function

Function myFunc2(var As Long) As Long
MsgBox var
End Function


You can even pass the first function call as the argument to the second,
like

myFunc2 myFunc1

Strictly speaking., the second does not need to be a function in this
example as you are n ot interested in its return result.
Other than that you can declare module level variable

Dim myVar

Sub Main()
myFunc1
myFunc2
End Sub

Sub myFunc1()
myVar = 17
End Sub

Sub myFunc2()
MsgBox myVar
End Sub


--

HTH

Bob Phillips
... looking out across Poole Harbour to the Purbecks
(remove nothere from the email address if mailing direct)
 

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