Variable scope

M

MikeB

I'm trying to use a variable to track the depth of nesting of
procedures, but am having difficulty. I thought I understood this from
the help, but apparently not.

Option Compare Database
Option Explicit

Sub MainSub()
Dim intNest As Integer
intNest = 0
Debug.Print intNest
SubNest1 intNest
Debug.Print intNest
SubNest2 intNest
Debug.Print intNest
End Sub

Sub SubNest1(intNest As Integer)
Debug.Print "." & intNest
intNest = intNest + 1
Debug.Print "." & intNest
End Sub

Sub SubNest2(intNest As Integer)
Debug.Print ".." & intNest
intNest = intNest + 1
Debug.Print ".." & intNest
SubSubNest2 intNest
Debug.Print ".." & intNest
End Sub

Sub SubSubNest2(intNest As Integer)
Debug.Print "+++" & intNest
intNest = intNest + 1
Debug.Print "+++" & intNest
End Sub


What I get from this is;

0
..0
..1
1
...1
...2
+++2
+++3
...3
3



What I was hoping to get was:
0
..0
..1
0
...0
...1
+++1
+++2
...1
0

How do I define variables so that they are local in scope to the
procedure using them? I tried using Private, but that wasn't allowed
inside a Sub.

Thanks
 
T

Tom van Stiphout

On Fri, 19 Sep 2008 06:56:16 -0700 (PDT), MikeB <[email protected]>
wrote:

If you have a procedure argument:
x as integer
that is equivalent to:
byref x as integer

In your case (and in most cases) you want:
byval x as integer

Look up the difference in the help file.

-Tom.
Microsoft Access MVP
 
B

bcap

A variable declared inside a procedure using Dim is automatically private to
that procedure, so the question of declaring it private doesn't arise.

I think what you are getting confused with is not scope as such but rather
how to pass arguments to a called procedure, which can be done in two ways,
by reference or by value.

If you pass a variable by reference, you are effectively passing the
*actual* variable, so if the called procedure changes it, then it is changed
for the calling procedure also. If you pass it by value, you are
effectively passing a *copy* of the variable, so if the called procedure
changes it then the original variable in the calling procedure is
unaffected.

You specify one or the other in the Sub statement, like this:

Sub SubNest1(ByVal intNest As Integer)

Or:

Sub SubNest1(ByRef intNest As Integer)

If you don't specify either ByVal or ByRef then the default is ByRef.
 

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