How to copy an array to another array

S

stephenc

I need to copy the content of a 2D array to another identical 2D array. I
currently do it this way...

for X=1 to 1000
for Y = 1 to 1000
A(X,Y) = B(X,Y)
next Y
next X

Is there a better/quicker way to do it?
 
K

Karl E. Peterson

stephenc said:
I need to copy the content of a 2D array to another identical 2D array. I
currently do it this way...

for X=1 to 1000
for Y = 1 to 1000
A(X,Y) = B(X,Y)
next Y
next X

Is there a better/quicker way to do it?

There are quicker ways, yes. But I'd be hard pressed to say they're
"better" unless you're optimizing a *serious* bottleneck.

I have a SafeArray class on my site that you can use to represent the
SAFEARRAY structure of any native array. You'd have to download that
(from http://vb.mvps.org/samples/MapFile), and use code something like
this (indented to highlight wordwrap):

Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory"
(Destination As Any, Source As Any, ByVal Length As Long)

Public Sub test()
Dim a() As Long
Dim b() As Long
Dim i As Long

Dim saA As CSafeArray
Set saA = New CSafeArray

Dim saB As CSafeArray
Set saB = New CSafeArray

ReDim a(1 To 100)
For i = LBound(a) To UBound(a)
a(i) = i
Next i

With saA
.AttachToArray a
ReDim b(.LowerBound To .LowerBound + .CountOfElements)
saB.AttachToArray b
Call CopyMemory(ByVal saB.PointerToData, _
ByVal .PointerToData, _
.SizeofElements * .CountOfElements)
End With

saA.ReleaseArray
saB.ReleaseArray
End Sub

Also, in CSafeArray, you'd want to redeclare the VarPtrArray function,
so that it works in VBA. This seems to do that, when I test here:

Private Declare Function VarPtrArray Lib "vbe6.dll" Alias "VarPtr"
(Var() As Any) As Long

Obviously, this is an *incredible* amount of work to go to, unless
you're saving some serious cycles in the process. Which is totally
possible! But if all you're trying to save is a bit of typing, well,
you'll want to reconsider more than a few things.

Hope this helps... Karl
 
D

Doug Robbins - Word MVP

A = B

--
Hope this helps.

Please reply to the newsgroup unless you wish to avail yourself of my
services on a paid consulting basis.

Doug Robbins - Word MVP, originally posted via msnews.microsoft.com
 
S

stephenc

Thanks Karl and Doug,
Sorry I didn't reply sooner but I thought I'd posted the question to the
Excel programming forum, and that the posting had failed. So, it was here in
the Word programming forum all the time. Doh!
Your replies answered my question exactly, so I've learned something useful
today. Thanks again for your help!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top