Suppose I have an array (1,2,3,4), then I want to copy it to another 1D array and 2D array. I use this sub-routine:
Sub CopyArray()
Dim Arr1(), Arr2()
ReDim Arr3(1 To m, 1 To n)
Arr1 = Array(1, 2, 3, 4)
For i = 1 To 4
Arr2(i) = Arr1(i)
Arr3(1, i) = Arr1(i)
Next i
End Sub
It kept getting an error "subscript out of range". I also tried
Sub CopyArray()
Dim Arr1(), Arr2()
Arr1 = Array(1, 2, 3, 4)
For i = 1 To 4
Arr2(i) = Arr1(i)
Next i
End Sub
or
Sub CopyArray()
Dim Arr1()
ReDim Arr3(1 To m, 1 To n)
Arr1 = Array(1, 2, 3, 4)
For i = 1 To 4
Arr3(1, i) = Arr1(i)
Next i
End Sub
but none of them worked. How does one copy 1D array to another 1D array and 2D array properly?
Simplest way to copy one array to another in your case would be to declare the arrays as Variant. This way you will not have to loop
Example of 1D array
Sub CopyArray()
Dim x As Variant
Dim y As Variant
x = Array(1, 2, 3)
y = x '<~~ Directly clone the array
For i = LBound(y) To UBound(y)
Debug.Print y(i)
Next i
End Sub
Example of 2D Array
Sub CopyArray()
Dim x As Variant
Dim y As Variant
x = Array(1, 2, 3)
y = Application.Transpose(x) '<~~ Transpose it
For i = LBound(y) To UBound(y)
Debug.Print y(i, 1)
Next i
End Sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With