How can I “ReDim Preserve” a 2D Array in Excel 2007 VBA so that I can add rows, not columns, to the array?

前端 未结 8 1502
梦如初夏
梦如初夏 2020-12-06 02:28

I\'m working with a dynamic array in Excel VBA. The number of columns (m) is fixed, however, I do not know how many rows (n) will be required.

The help documents st

8条回答
  •  执念已碎
    2020-12-06 02:56

    One way to do what you want is to use a 1-D array that contains 1-D arrays instead of a 2-D array. Then you can ReDim Preserve the outer array all you want. If you're returning the outer array from a function, Excel will do the right thing and coerce it to a 2-D array.

    For example, the function below will return a 3x2 array to the cells it's called from:

    Public Function nested()
        Dim outer
        outer = Array(Array(1, 2), Array(3, 4))
    
        ReDim Preserve outer(1 To 3)
    
        outer(3) = Array(5, 6)
    
        nested = outer
    End Function
    

    My answer to these questions might also be useful to you: Pass multidimensional array into Excel UDF in VBA and VBA pasting 3 dimensional array into sheet

    Of course, if you're not returning this from a UDF, you'll have to coerce it yourself. An easy way to do that without writing looping code is to do this:

    Dim coerced
    coerced = Application.Index(outer, 0, 0)
    

    This is just calling Excel's built-in INDEX function, and the zeros mean that you want back all of your rows and all of your columns. Excel will coerce your 1-D array of 1-D arrays to a 2-D array automatically. (Caveat: there are some size limitations, but they are much bigger than 10x20.)

提交回复
热议问题