Хотя использование коллекций или словарей может быть лучшим вариантом для поэтапного добавления элементов, бывают ситуации, когда проще просто увеличить массив.
Функция для отправки в массив
Вот функция, которая может добавить элемент или даже несколько элементов в конец массива.Я основал это на том, как работает метод JavaScripts push
.
' Mutates array by adding element(s) to the end of an array. Returns the new array length.
Public Function ArrayPush(ByRef sourceArray As Variant, ParamArray elements() As Variant) As Long
'@author: Robert Todar <https://github.com/todar>
'@param: <SourceArray> must be a single dimensional array.
'@param: <elements> are the elementss to be added.
' Change this if you prefer to work with option base 1
Const optionBase As Long = 0
Dim firstEmptyBound As Long
Select Case ArrayDimensionLength(sourceArray)
Case 0
firstEmptyBound = optionBase
' Create space for new elements in empty array.
ReDim sourceArray(optionBase To UBound(elements, 1) + optionBase)
Case 1
firstEmptyBound = UBound(sourceArray) + 1
' Add more space for new elements.
ReDim Preserve sourceArray( _
LBound(sourceArray) To UBound(sourceArray) + UBound(elements) + 1)
Case Else
Err.Raise 5, "ArrayPush", "ArrayPush function only works with single dimension arrays."
End Select
Dim index As Long
For index = LBound(elements) To UBound(elements)
' Add elements to the end of the array. Assign is to 'set' or 'let' depending on type.
If IsObject(elements(index)) Then
Set sourceArray(firstEmptyBound) = elements(index)
Else
Let sourceArray(firstEmptyBound) = elements(index)
End If
' Increment to the next empty index
firstEmptyBound = firstEmptyBound + 1
Next index
' Return new array length
ArrayPush = UBound(sourceArray) + (Int(optionBase = 0) * -1) - LBound(sourceArray)
End Function
Эта функция также использует вспомогательную функцию ArrayDimensionLength
, чтобы гарантировать, что массив был передан и что это только одно измерение.
' Returns the length of the dimension of an array.
Public Function ArrayDimensionLength(ByVal sourceArray As Variant) As Long
On Error GoTo Catch
Do
Dim boundIndex As Long
boundIndex = boundIndex + 1
' Loop until this line errors out.
Dim test As Long
test = UBound(sourceArray, boundIndex)
Loop
Catch:
' Must remove one, this gives the proper dimension length.
ArrayDimensionLength = boundIndex - 1
End Function
Пример использования этой функции
Вы можете добавлять отдельные элементы одновременно или несколько одновременно.Просто обратите внимание, что он должен ReDim
массив каждый раз, так что помните об этом при использовании его с большими циклами.
Private Sub testArrayPush()
Dim data() As String
' Single element
ArrayPush data, "apple"
' Multiple elements
ArrayPush data, "banana", "carrot"
Debug.Print Join(data, ", ") '<~ apple, banana, carrot
End Sub
Вы можете найти эту функцию и другие подобные функции массива на моем GitHubPage .