VBA private sub in private sub?

Dimitris254

Board Regular
Joined
Apr 25, 2016
Messages
139
Hi all,

i'd like to know if it's possible to nest a private sub in another private sub. I don't want one of the sub to be public or something. The code would looks something like this:

Rich (BB code):
Sub main_sub()
Call sub_parent​
End Sub --------------------- Private Sub sub_parent()
Call sub_child​
Private Sub sub_child() ... End Sub End Sub

The reason i want the sub_child in sub_parent is so that they can see each other's variables. :(
 

Excel Facts

Which Excel functions can ignore hidden rows?
The SUBTOTAL and AGGREGATE functions ignore hidden rows. AGGREGATE can also exclude error cells and more.
No you can't nest Subs. For each sub to see the variable just declare them at module level. Paste this into an empty code window and run the setvariable macro:

Code:
Dim sVariable1 As String

Sub SetVariable()
    sVariable1 = "Here I am"
    ReadVariable
End Sub


Private Sub ReadVariable()
    MsgBox sVariable1
End Sub
 
Upvote 0
Hi

Remark: if you just want to share the variables in the module procedures you can define the variables as Private

Code:
Option Explicit
Private s As String

Sub Main_sub()

...
 
Upvote 0
yes, i'm aware of the scope of variables and that's what troubled me, but i've seen that if i declare only 2 variables public, then it should be ok

however, a follow up question is: can a private sub call another private sub?
 
Upvote 0
Best way is to try it, but yes. My code does just that. The SetVariable sub calls the ReadVariable sub. However they must both reside in the same module
 
Upvote 0

Forum statistics

Threads
1,215,500
Messages
6,125,168
Members
449,211
Latest member
ykrcory

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