Purpose:
Given a 2-Dimensional Array, return a copy of the Array. In VBA, if I just
Set newArray = oldArray
then newArray
is simply a pointer to oldArray
rather than an independent copy, hence this function.
Method:
Assign Array bounds. Create identically-sized Array. Iterate over Array and copy each element value.
Specific Areas of Interest:
The function feels very generic. The naming even more so. But then again it's supposed to be very generic. Is the naming alright or could it be better?
Function:
Private Function CopyOf2DArray(ByRef targetArray As Variant) As Variant
'/ Will error if the array contains objects
Dim LB1 As Long, UB1 As Long
Dim LB2 As Long, UB2 As Long
AssignArrayBounds targetArray, LB1, UB1, LB2, UB2
Dim newArray As Variant
ReDim newArray(LB1 To UB1, LB2 To UB2)
Dim i As Long, j As Long
For i = LB1 To UB1
For j = LB2 To UB2
newArray(i, j) = targetArray(i, j)
Next j
Next i
CopyOf2DArray = newArray
End Function
oldArray
thennewArray = oldArray
. No setting or redimming or looping required. What yourCopyOf2DArray
would be good for (with some minor modifications) is creating a transposed copy ofoldArray
that does not have the unsigned int limitations that the native Transpose does. See my_2D_Transpose(a1 As Variant, a2 As Variant). \$\endgroup\$