我想在 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
答案1
我通过使用 Collection 然后将其复制到数组来解决了该问题。
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
答案2
尝试这个[编辑]:
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
答案3
这是我使用 Variant(数组)变量的方法:
Dim a As Range
Dim arr As Variant 'Just a Variant variable (i.e. don't pre-define it as an array)
For Each a In Range.Cells
If IsEmpty(arr) Then
arr = Array(a.value) 'Make the Variant an array with a single element
Else
ReDim Preserve arr(UBound(arr) + 1) 'Add next array element
arr(UBound(arr)) = a.value 'Assign the array element
End If
Next
或者,如果你确实需要一个变量数组(例如,传递给 Shapes.Range 之类的属性),那么你可以这样做:
Dim a As Range
Dim arr() As Variant
ReDim arr(0 To 0) 'Allocate first element
For Each a In Range.Cells
arr(UBound(arr)) = a.value 'Assign the array element
ReDim Preserve arr(UBound(arr) + 1) 'Allocate next element
Next
ReDim Preserve arr(LBound(arr) To UBound(arr) - 1) 'Deallocate the last, unused element
答案4
谢谢。如果这能帮助到像我一样的其他新手,我会用 2 个函数做同样的事情:
收藏
Function toCollection(ByVal NamedRange As String) As Collection
Dim i As Integer
Dim col As New Collection
Dim Myrange As Variant, aData As Variant
Myrange = Range(NamedRange)
For Each aData In Myrange
col.Add aData '.Value
Next
Set toCollection = col
Set col = Nothing
End Function
一维数组:
Function toArray1D(MyCollection As Collection)
' See http://superuser.com/a/809212/69050
If MyCollection Is Nothing Then
Debug.Print Chr(10) & Time & ": Collection Is Empty"
Exit Function
End If
Dim myarr() As Variant
Dim i As Integer
ReDim myarr(1 To MyCollection.Count) As Variant
For i = 1 To MyCollection.Count
myarr(i) = MyCollection(i)
Next i
toArray1D = myarr
End Function
用法
Dim col As New Collection
Set col = toCollection(RangeName(0))
Dim arr() As Variant
arr = toArray1D(col)
Set col = Nothing