tiredofit
Well-known Member
- Joined
- Apr 11, 2013
- Messages
- 1,926
- Office Version
- 365
- 2019
- Platform
- Windows
According to Chip Pearson:
arrays are ALWAYS passed ByRef. If you attempt to pass ByVal, you'll encounter a compilation error.
Here is his code:
In my worksheet, I have the following:
This is my code:
which returns the value of 10 because the Sub b was passed ByRef and has changed the array's value.
If I wrote this, it would NOT compile, as per Chip Pearson's article:
However, if I omitted the brackets, like this:
it returns the value of 1, as "sort of" expected because Sub b was passed ByVal.
So in my last example, have I passed an array ByVal or have I passed something else ByVal?
Thanks
Rich (BB code):
arrays are ALWAYS passed ByRef. If you attempt to pass ByVal, you'll encounter a compilation error.
Here is his code:
Rich (BB code):
Option Explicit
Sub AAATest()
Dim StaticArray(1 To 3) As Long
Dim N As Long
StaticArray(1) = 1
StaticArray(2) = 2
StaticArray(3) = 3
PopulatePassedArray Arr:=StaticArray
For N = LBound(StaticArray) To UBound(StaticArray)
Debug.Print StaticArray(N)
Next N
End Sub
Sub PopulatePassedArray(ByRef Arr() As Long)
''''''''''''''''''''''''''''''''''''
' PopulatePassedArray
' This puts some values in Arr.
''''''''''''''''''''''''''''''''''''
Dim N As Long
For N = LBound(Arr) To UBound(Arr)
Arr(N) = N * 10
Next N
End Sub
In my worksheet, I have the following:
Rich (BB code):
1
2
3
This is my code:
Rich (BB code):
Sub a()
Dim MyArray() As Variant
MyArray = Cells(1, 1).CurrentRegion.Value
Call b(MyArray)
Debug.Print MyArray(1, 1)
End Sub
Sub b(ByRef abc() As Variant)
abc(1, 1) = 10
End Sub
which returns the value of 10 because the Sub b was passed ByRef and has changed the array's value.
If I wrote this, it would NOT compile, as per Chip Pearson's article:
Rich (BB code):
Sub a()
Dim MyArray() As Variant
MyArray = Cells(1, 1).CurrentRegion.Value
Call b(MyArray)
Debug.Print MyArray(1, 1)
End Sub
Sub b(ByVal abc() As Variant)
abc(1, 1) = 10
End Sub
However, if I omitted the brackets, like this:
Rich (BB code):
Sub a()
Dim MyArray() As Variant
MyArray = Cells(1, 1).CurrentRegion.Value
Call b(MyArray)
Debug.Print MyArray(1, 1)
End Sub
Sub b(ByVal abc As Variant)
abc(1, 1) = 10
End Sub
it returns the value of 1, as "sort of" expected because Sub b was passed ByVal.
So in my last example, have I passed an array ByVal or have I passed something else ByVal?
Thanks