在VBA中将元素添加到数组的末尾

时间:2018-09-15 19:26:05

标签: arrays vba element

问与答: 如何在VBA中的(动态)数组的末尾添加元素?

同一问题是要获取列表而不是数组: Adding an element to variant list/array in VBA 同样的问题是关于重新定义二维数组: ReDiming an array in VBA 这个问题并没有要求一般的简单情况:https://superuser.com/questions/808798/adding-an-element-to-the-end-of-an-array

2 个答案:

答案 0 :(得分:1)

这是一个简短的VBA代码,用于:

  1. 创建动态数组。
  2. 将动态数组重新分配为3个元素。
  3. 用值填充新添加的元素。

    Sub ChangingArrayLengthShort()
        ' First create array:
        Dim arr() As Variant
        Dim u As Integer
        u = 3
    
        ReDim arr(1 To u + 1) ' Redimension:
        arr(UBound(arr)) = "SomeValue" ' Fill last element
    End Sub
    

这是解释的代码:

Sub ChangingArrayLength()
    Dim arr() As Variant ' One can only redimension a dynamic array, so:
    'Dim arr(43 to 65) As Variant ' Will yield an error since it is not a dynamic- but a static array.

    Dim NrOfElements As Integer

    NrOfElements = 3
    ReDim arr(1 To NrOfElements) ' Re-dimension array length
    MsgBox (UBound(arr)) ' Show what the last element index is in array arr.

    NrOfElements = NrOfElements + 1 ' Increase the variable that is used to increase the nr of elements in array arr.
    ReDim arr(1 To NrOfElements) ' Re-dimension array length
    MsgBox (UBound(arr)) ' Show what the last element index is in array arr. (And that it increased by 1)

    ' Add value at element to the end of an array:
    arr(UBound(arr)) = "This string is added as last element of array named arr"
End Sub

答案 1 :(得分:1)

我已经遇到了这个问题,我已经解决了

 aArray(Array.IndexOf(aArray, aArray.Last)) 'this same reDim action for resize

它还解决了reDim的错误