Is there a way to join a collection in VBA? I can find join(array, ";"), but this function can not be applied to a collection.
Thanks.
Is there a way to join a collection in VBA? I can find join(array, ";"), but this function can not be applied to a collection.
Thanks.
Unfortunately, no, there's nothing built-in.
You'll have to either
convert the collection to an array (no built-in for that either, you'll have to loop through all the items) and then use Join(array, ";")
or
join your collection "the hard way" (set first
flag, loop through items, add ";" if not first
, clear first
, add item).
This is how to join it:
Join(CollectionToArray(colData), ",")
And the function:
Public Function CollectionToArray(myCol As Collection) As Variant
Dim result As Variant
Dim cnt As Long
ReDim result(myCol.Count - 1)
For cnt = 0 To myCol.Count - 1
result(cnt) = myCol(cnt + 1)
Next cnt
CollectionToArray = result
End Function
You don't need to use an array.
Just concatenate each element of the collection with chosen delimeter.
Function collectionToString(coll As Collection, delim As String) As String
Dim element
Dim out As String
For Each element In coll
out = IIf(out = "", element, out & delim & element)
Next
collectionToString = out
End Function
I need to clarify that the following is NOT the answer to the question above. However, for anyone who arrived here wondering how to merge collections (happened to me), the code below will add the contents of a collection (col2) to another (col1):
Sub addColToCol(col1 As Collection, col2 As Collection)
Dim i As Integer
For i = 1 To col2.Count
col1.Add col2.Item(i)
Next i
End Sub
If you want to preserve the contents of each collection, declare an additional collection.
Dim super_col As New Collection
addColToCol super_col, col1
addColToCol super_col, col2
© 2022 - 2024 — McMap. All rights reserved.
List.ToString
method would do what you want to do here. – Quandary