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)
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)
归档时间: |
|
查看次数: |
272288 次 |
最近记录: |