Calling another sub() in VBA

cwunderlich

Board Regular
Joined
Sep 24, 2010
Messages
101
I have a sub routine that is run. Within this sub routine, a number of variables are declared and stored with certain values. I then would like to call a second sub routine, let's call it "SecondSub".

Within the first sub routine, I have the code in place to call the SecondSub (Call SecondSub).

My question is this: what needs to be done for those variables that were stored in the original sub routine to be able to be used in the SecondSub that is called by the original?

Thanks,
 

Excel Facts

Can a formula spear through sheets?
Use =SUM(January:December!E7) to sum E7 on all of the sheets from January through December
Declare them outside the procedures

Code:
Public Var1 as Long
Public Var2 as String
 
Sub RunSub1
 
'...code
'...code
'...code
 
Call SubRun2
End Sub
 
Sub SubRun2
'will now have access to Var1 and Var2 as defined in SubRun1
End Sub
 
Upvote 0
I figured it was something simple like that... I knew I had done it before, but just couldn't remember what I did.... thanks a lot!
 
Upvote 0
if you are declaring the variables in the first sub then use this:

Code:
Sub subOne()
    Dim var1 As Long
    Dim var2 As Long
    
    'code
    
    subTwo var1, var2
End Sub

Sub subTwo(ByVal v1 As Long, ByRef v2 As Long)
    'code
End Sub

note the "ByVal" and "ByRef" in this line "Sub subTwo(ByVal v1 As Long, ByRef v2 As Long)"

ByVal means that only the value is passed to subTwo and subTwo cannot change the value

ByRef means that a reference is passed to subTwo so subTwo can change the value of the variable and subOne will have access to the changed value
 
Upvote 0

Forum statistics

Threads
1,213,489
Messages
6,113,949
Members
448,534
Latest member
benefuexx

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top