View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
Tom Ogilvy Tom Ogilvy is offline
external usenet poster
 
Posts: 6,953
Default Passing Arrays to SUBs

Basically Arrays are passed by reference. However, you can make the
argument a variant (no an array) and pass you array byval.

Sub Tester1()
Dim v(1 To 10)
For i = 1 To 10
v(i) = i
Next
HandleArray v
s = ""
For i = 1 To 10
s = s & v(i) & ","
Next
MsgBox s
End Sub

Sub HandleArray(ByVal arr)
s = ""
For i = 1 To 10
s = s & arr(i) & ","
Next
MsgBox "Enter HandleArray: " & s
s = ""
ReDim arr(0 To 4)
For i = LBound(arr) To UBound(arr)
arr(i) = 20
Next
For i = LBound(arr) To UBound(arr)
s = s & arr(i) & ","
Next
MsgBox "Leaving HandleArray: " & s
End Sub

as long as you don't do that, it should be byref. Probably best to
explicitly declare the argument as byref.

--
Regards,
Tom Ogilvy




"Bill Martin" wrote:

I have code which seems to work properly, but I'm slightly nervous as I
haven't seen it actually written anywhere how this works. Basically the
question is how do arrays get passed as parameters to a SUB() ?

I've set up a toy routine that near the top says: Dim TestVector(10) As
Long

And later I pass it to a SUB like this: Call TestRoutine(TestVector)

Apparently the TestRoutine gets compiled as if it also had that same
typing/sizing for TestVector. In fact if I try to force it to some
conflicting typing it compiles ok, but crashes with an error as the CALL
gets executed.

From putzing around with this toy setup a bit I've sort of concluded that
VBA passes parameters to it's SUBs using "call by reference" rather than
"call by value". Is this true? Am I safe to pass arrays to subroutines as
in the CALL example above without specifying typing or sizing anywhere?
Those things magically pass themselves? And if it were a large array, then
all the data cells aren't really getting passed but rather only the
reference to the array?

I figured I should ask about this before I dig myself too big a hole and
THEN find out there's a gotcha somewhere in there. Thanks...

Bill