Simple Question on Variable Scope

  • Thread starter Thread starter Dave
  • Start date Start date
D

Dave

I need to call a sub procedure and have it assign a value to a variable that
will be available throughout a module.

I can call a function and have it return a value to the calling procedure.
But I cannot call a procedure from another procedure, have it change the
value of a variable and then be able to reference this variable in other
procedures within the module.

For example, in the code below, the value of "bln" is true in the called
proc but in the calling proc it is empty.

What don't I understand?

Dave
-------------------

'Private bln As Boolean
Public bln As Boolean

Private Sub Command41_Click()

IsItEven (txtX)
Debug.Print "Calling Proc = " & bln

End Sub


'Private Sub IsItEven(ByRef x As Integer)
'Private Sub IsItEven(ByVal x As Integer)
Private Sub IsItEven(x As Integer)

If x Mod 2 = 0 Then
bln = True
Else
bln = False
End If

Debug.Print "Called Proc = " & bln

End Sub
 
What you've posted, assuming that all of the code is in the same module,
should work as you desire.

Be sure that you don't have other variables in other procedures in this
module that also Dim bln as a local variable.
 
I can't reproduce this. I copied and pasted your code, the only thing I
changed was the names of the controls, as follows ...

Option Compare Database
Option Explicit

'Private bln As Boolean
Public bln As Boolean

Private Sub cmdTest_Click()

IsItEven (txtTest)
Debug.Print "Calling Proc = " & bln

End Sub

'Private Sub IsItEven(ByRef x As Integer)
'Private Sub IsItEven(ByVal x As Integer)
Private Sub IsItEven(x As Integer)

If x Mod 2 = 0 Then
bln = True
Else
bln = False
End If

Debug.Print "Called Proc = " & bln

End Sub

Here are my results, first with the value "2" in the text box (x Mod 2 = 0
evaluates to True) and then with the value "3" in the text box (x Mod 2 = 0
evaluates to False) ...

Called Proc = True
Calling Proc = True
Called Proc = False
Calling Proc = False

By the way, a Boolean variable can never, under any circumstances, have the
value Empty. Only a Variant can have that value.
 
Thanks guys

Dumb question but does the variable declaration have to precede the
procedure in the module?

IOW Do I have to declare module level variables before I write any
functions/procedures?
 
Yes. The Dim statement must go in the Declarations section of the module,
the section between any Option statements and the first sub or function in
the module.
 
Ah so.. thank you for clearing that up

Dave


Ken Snell said:
Yes. The Dim statement must go in the Declarations section of the module,
the section between any Option statements and the first sub or function in
the module.
 
Back
Top