Is there a way to copy the contents of one array to another without using a loop?
eg. MyArr1() = MyArr2()
Printable View
Is there a way to copy the contents of one array to another without using a loop?
eg. MyArr1() = MyArr2()
i don't think there is. :( im not sure though
but perhaps a variant variable (holds an array aw well) is good ;)
like
VB Code:
Dim myArr(4) As String Dim myVar As Variant 'initialize myArr or whatever myVar = myArr 'try this one if ok :D Msgbox CStr(UBound(myVar))
Try this:
VB Code:
Option Explicit Private Sub Form_Load() Dim t() As Integer, y() As Integer Dim x As Integer, str$ ReDim t(4) As Integer For x = 0 To 3 t(x) = x Next x y() = t() For x = 0 To 3 str = str & y(x) Next x MsgBox str End Sub
Without a loop...
VB Code:
Option Explicit Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long) Private Sub Form_Load() Dim Arr1(100) As Long Dim Arr2() As Long ReDim Arr2(UBound(Arr1)) CopyMemory Arr2(0), Arr1(0), Len(Arr1(0)) * (UBound(Arr1) + 1) End Sub
via CVMicheal
Mine copies the array without a loop. The loops just load and display data.
Thanks All. Got it working the way I want :D
Darn, the VBForums sever was down when I had this code to post:
VB Code:
Option Explicit Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long) Private Sub Copy_Array_Long(Destination() As Long, Source() As Long, Length As Long) CopyMemory Destination(0), Source(0), Length End Sub Private Sub Form_Activate() Dim A(3) As Long, B(3) As Long A(0) = 10: A(1) = 20: A(2) = 30 Copy_Array_Long B(), A(), Len(A(0)) * UBound(A) Print B(0), B(1), B(2) End Sub
Slightly more versatile version of Jake's function
VB Code:
Private Sub CopyLongArray( _ ByRef psaDestination() As Long, _ ByRef psaSource() As Long _ ) CopyMemory psaDestination(LBound(psaSource)), _ psaSource(UBound(psaSource)), _ (UBound(psaSource) - LBound(psaSource)) * LenB(psaSource(LBound(psaSource))) End Sub
I'm using the code submitted by |2eM!x but my question is can I use that code for a 2D Array?
eg MyArr(6,10)
Offhand I don't know how 2D arrays are stored in memory so I couldn't help you with CopyMemory there.
If you declare the arrays as dynamic and subsequently ReDim the source array to the dimensions you want then you can just equate it with the destination array.
e.g.
VB Code:
Dim lArrSrc() As Long Dim lArrDest() As Long ReDim lArrSrc(6,10) ' later lArrDest = lArrSrc
It only works with dynamic arrays.
Thanks penagate...that's what I was after.
No worries :)