在数组末尾添加一个元素

meg*_*off 15 vba microsoft-excel

我想在 VBA 数组的末尾添加一个值。我怎样才能做到这一点?我在网上找不到一个简单的例子。这是一些伪代码,显示了我希望能够做什么。

Public Function toArray(range As range)
 Dim arr() As Variant
 For Each a In range.Cells
  'how to add dynamically the value to end and increase the array?
   arr(arr.count) = a.Value 'pseudo code
 Next
toArray= Join(arr, ",")
End Function
Run Code Online (Sandbox Code Playgroud)

meg*_*off 11

我通过使用集合解决了这个问题,然后将其复制到数组中。

Dim col As New Collection
For Each a In range.Cells
   col.Add a.Value  '  dynamically add value to the end
Next
Dim arr() As Variant
arr = toArray(col) 'convert collection to an array

Function toArray(col As Collection)
  Dim arr() As Variant
  ReDim arr(0 To col.Count-1) As Variant
  For i = 1 To col.Count
      arr(i-1) = col(i)
  Next
  toArray = arr
End Function
Run Code Online (Sandbox Code Playgroud)

  • 如果您打算使用集合,您不妨使用字典对象。` Set col = CreateObject("Scripting.Dictionary") ` 然后你可以直接将 Keys 输出为数组并跳过你添加的函数: ` arr = col.keys ` <= Array (3认同)

Leo*_*iro 10

试试这个[编辑]:

Dim arr() As Variant ' let brackets empty, not Dim arr(1) As Variant !

For Each a In range.Cells
    ' change / adjust the size of array 
    ReDim Preserve arr(1 To UBound(arr) + 1) As Variant

    ' add value on the end of the array
    arr (UBound(arr)) = a.value
Next
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,但它仍然不能以这种方式工作,因为如前所述,`UBound(arr)` 需要一个已经有维度的数组。好吧,看来我必须改用集合。还是很感谢你 (2认同)