I've got a 3-dimensional array, call it Arr(25,10,10), where I want to copy all contents of a given first index to another first index, e.g. Arr(6,-,-) to Arr(17,-,-). I'd like to do this without using For..Next loops every time. I think what I need is to change the array structure so it becomes a 1-dimensional array (Arr(25)) having a 2-dimensional array (Arr2(10,10)) as its elements, but I'm not sure how to do that. How do I Dim the array and how do I copy one index to another? Any help appreciated.
-
Why not just use a loop? VBA doesn't have a lot of useful array-oriented methods, so a loop is often the "best" way to get something done without involving (eg) worksheet functions (which have terrible performance when used in for VBA arrays vs. against a worksheet)Tim Williams– Tim Williams2019-10-05 23:02:46 +00:00Commented Oct 5, 2019 at 23:02
-
@Tim Williams Well, it just seems very inefficient. I need to do this procedure perhaps millions of times. Isn't it much faster to set one array equal to another rather than populating the array with For..Next loops?Jens– Jens2019-10-05 23:10:13 +00:00Commented Oct 5, 2019 at 23:10
-
Maybe yes, if there were some built-in way to do that. Array loops are pretty fast, so "inefficient" isn't really a problem here. However, there's no problem having an array of arrays in VBA - you can arrange them as nested as you need.Tim Williams– Tim Williams2019-10-05 23:19:55 +00:00Commented Oct 5, 2019 at 23:19
-
@Tim Williams Could you show me how to Dim such an array and how to copy one element to another? Thanks!Jens– Jens2019-10-05 23:31:05 +00:00Commented Oct 5, 2019 at 23:31
Add a comment
|
2 Answers
This uses a Type to define the two-D array, and then packs it within the 1-D array
Option Explicit
Type Ta2D
a2D(1 To 10, 1 To 10)
End Type
Sub ArraySlicing_take3()
Dim a1D(1 To 25) As Ta2D
'Populate a sample 3-D array with values...
Dim x, y, z
For z = 1 To 25
For y = 1 To 10
For x = 1 To 10
a1D(z).a2D(y, x) = "D" & z & "R" & y & ":C" & x
Next x
Next y
Next z
'...done setting up sample array
Dim w(1) As Ta2D
w(1) = a1D(6)
a1D(17) = w(1)
End Sub
'