0

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.

4
  • 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) Commented 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? Commented 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. Commented 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! Commented Oct 5, 2019 at 23:31

2 Answers 2

1

If you want to restructure your array you can do something like this:

Sub Tester()

    Dim arr(25)
    Dim i As Long

    For i = 0 To 25
        Dim a(10, 10)
        arr(i) = a
    Next i

    arr(6)(1, 1) = 99
    arr(17)(1, 1) = 88

    arr(17) = arr(6)

    Debug.Print arr(17)(1, 1) '>> 99

End Sub
Sign up to request clarification or add additional context in comments.

Comments

1

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

'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.