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

前端 未结 8 1508
梦如初夏
梦如初夏 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 03:13

    One way how you could sove it is indeed by a double transpose with a change on the number of columns in between. This will however only work for two-dimensional arrays. It is done as follows:

    ' Adding one row is done by a double transposing and adding a column in between.
    ' (Excel VBA does not allow to change the size of the non-last dimension of a
    ' multidimensional array.)
    myArray = Application.Transpose(myArray)
    ReDim Preserve myArray(1 To m, 1 To n + 1)
    myArray= Application.Transpose(myArray)
    

    Of course m and n can be deduced as follows:

    m = UBound(myArray, 1)
    n = UBound(myArray, 2)
    

    So you use the built-in transpose functionality of Excel itself. As mentioned in the code comments, this will not work for higher order matrices.

提交回复
热议问题