Passing Arrays ByVal or ByRef?

S

StevenM

As a habit, I normally pass variables to functions "ByVal." But I was
wondering if it was faster/better to pass an array "ByRef" even if one wasn't
planning to modify its contents? Doesn't "ByVal" create a new array of the
same size?

Also, it appeared to me that to pass an array, one has to use a Variant
variable, is that correct?

The following code seemed to work as expected.

Sub ArrayTest()
Dim arrayX(4 To 99) As Byte

arrayX(4) = 11
arrayX(5) = 99
Call PassArray(arrayX, arrayX)
MsgBox arrayX(4)
MsgBox arrayX(5)
End Sub

Function PassArray(ByVal arrayY As Variant, ByRef arrayZ As Variant)
MsgBox "The Bounds of this array is: " & LBound(arrayY) & " and " &
UBound(arrayY)
MsgBox arrayY(4)
arrayY(4) = 66
arrayZ(5) = 88
End Function

Steven Craig Miller
 
G

George Lee

ByRef is generally faster, since it’s passing a pointer rather than a copy of
the object. Is this better, is harder to say. You can end up changing the
entire contents, even discarding the object itself, by accident. It’s
considered good programming practice to return changes as part of a function,
anyway. This makes debugging easier and program flow more clear. VB6 and VBA
aren’t languages you use because they’re fast, so the overhead of using ByVal
is safe.

As for passing arrays as parameters, no you can pass them as their own type.
But it must be ByRef. In fact, it’s a design time error not to.

Sub ArrayTest2()
Dim arrayX(4 To 99) As Byte
arrayX(4) = 11
arrayX(5) = 99
PassArray2 arrayX
MsgBox arrayX(4) & " " & arrayX(5)
End Sub

Sub PassArray2(ByRef arrayY() As Byte)
arrayY(4) = 66
arrayY(5) = 88
End Sub
 

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