ByVal or ByRef - Arrays

When you declare a variable with an Array data type it can only be passed in using ByRef.
The Array data type is a Value data type.


ByRef

Passing an Array into a subroutine using ByRef allows the original variable to be changed.

Public Sub Passing_Arrays() 
   Dim myArray(3) As Integer
   myArray(0) = 1
   myArray(1) = 2
   myArray(2) = 3
   myArray(3) = 4
   Debug.Print myArray(2) '3

   Call ByReference(myArray) 'must use Call
   Debug.Print myArray(2) '8
End Sub

'must be ByRef
Public Sub ByReference(ByRef myArray2() As Integer)
'this changes the original
   myArray2(2) = 8
   
'this changes the original
   myArray2(2) = 8
End Sub

ByVal

Passing an Array into a subroutine using ByVal is not possible.
If you try and declare an array parameter that is passed ByVal you will get a compile error

Public Sub ByValue(ByVal myArray2() As Integer) 
End Sub

SS - array argument must be byref



© 2021 Better Solutions Limited. All Rights Reserved. © 2021 Better Solutions Limited TopPrevNext