# Passing Array to Sub



## DavidWalsh

I want to be able to run a sub on different arrays that will be dynamic. How can I do this so that the original array is modified.

Thanks for any help.


----------



## OBP

What language?


----------



## jiml8

You need to pass the array by reference, not by value. Usually this is the default anyway for most languages, but the syntax depends on the language.


----------



## DavidWalsh

Sorry, yes, should have said. VB6.


----------



## cristobal03

You can pass arrays ByRef, but I believe you can return arrays ByVal (at least, you can in VBA).



Code:


' calling procedure
Sub SomeCaller()
  Dim vaByRefArray()  As Variant
  Dim vaByValArray()  As Variant
  Dim i               As Integer

  ReDim vaByRefArray(19)

  Call ByRefRoutine vaByRefArray
  vaByValArray = ByValRoutine()

  For i = 0 To UBound(vaByRefArray)
    Debug.Print vaByRefArray(i)
  Next i

  For i = 0 To UBound(vaByValArray)
    Debug.Print vaByRefArray(i)
  Next i
End Sub


======

Sub ByRefRoutine(ByRef MyArray() As Variant)
  Dim i As Integer

  For i = 0 To UBound(MyArray)
    MyArray(i) = i ^ 2
  Next i
End Sub


======

Function ByValRoutine() As Variant()
  Dim MyArray()  As Variant
  Dim i          As Integer

  ReDim MyArray(19)

  For i = 0 To UBound(MyArray)
    MyArray(i) = i / 2
  Next i

  ByValRoutine = MyArray
End Function

Like I said, that'll work in VBA, but I don't know about strict VB.

chris.


----------



## Ken Puls

Hi there,

Like Chris says, I don't believe you'll have an issue porting VBA code to VB, but if you want to be sure, Mark Rowlison has a great article on his site here: http://www.thecodenet.com/articles.php?id=6

Hope it helps,


----------



## RGregory

I believe arrays are passed byref as default in VB6... You can always specify byRef in the parameters though, to ensure that you want to work on the actual variables and not copies.


----------



## DavidWalsh

Thanks for the replies. I shall be having a look at implementing the methods that you you have suggested at sometime over the next few days. I'll let you know how I get on.


----------

