Archive of Mr Excel Message Board
"As a result, the variable's actual value can be changed by the procedure to which it is passed. Unless otherwise specified, arguments are passed by reference."
But for example, in the following simple code, this does not seem to be the case:
-----
Sub sub1()
Dim i As Integer
i = 10
MsgBox (i)
sub2 (i)
MsgBox (i)
End Sub
Sub sub2(ByRef i as Integer)
i = 20
End Sub
-----
If I run "sub1", both message boxes show "10". Why was sub2 not able to change i to 20? I cant figure it out! VBA Help, like I quoted above, said that it should!

| Check out our Excel VBA Resources | ||||
![]() |
![]() |
![]() |
![]() |
![]() |
Try this:
Dim i As Integer
Sub sub1()
i = 10
MsgBox (i)
sub2
MsgBox (i)
End Sub
Sub sub2()
i = 20
End Sub
Put the Dim i above both subs and you dont call with variables this will retain the values between subs.
HTH
Jacob

A long time ago when I used to program a little in C, you would "pass a pointer". That is basically what I want to do.
I am a large program, and if I use global variables it will be a horrible mess. i = 10 MsgBox (i) sub2 MsgBox (i) i = 20

Also declaring varibles at the module level as Jacob suggested
allows only the variable to be avail to that module only, unless declared as Public. So it won't
be a horrible mess
You can use the Private statement to declare private module-level variables.
Private variables can be used only by procedures in the same module.
BUT When used at the module level, the Dim statement is equivalent to the Private statement. You might want to use the Private statement to make your code easier to read and interpret
so code reads;
Sub sub1()
Dim i As Integer
i = 10
MsgBox i
sub2 i
MsgBox i
End Sub
Sub sub2(i As Integer)
i = 20
End Sub
HTH
Ivan But that creates a global variable, that is what I DONT want. I want to pass a reference and change the actual value of the variable. According to all documentation I read, this should be possible. A long time ago when I used to program a little in C, you would "pass a pointer". That is basically what I want to do. I am a large program, and if I use global variables it will be a horrible mess. : Hi : Try this

Sub sub1()
Dim i As Integer
i = 10
MsgBox i
sub2 i
MsgBox i
End Sub
Sub sub2(i As Integer)
i = 20
End Sub
Juan Pablo G. The syntax is not correct
