如何在 VBA 中加入 collection

How to join a collection in VBA

有没有办法在VBA中加入collection? 我可以找到 join(array, ";"),但是这个函数不能应用于 collection.

谢谢。

很遗憾,没有,什么都没有built-in。

你必须

  • 将 collection 转换为数组(也没有 built-in,你必须 loop through all the items)然后使用 Join(array, ";")

  • 加入你的collection"the hard way"(设置first标志,遍历项目,添加“;”如果没有first,清除first, 添加项目).

我需要澄清以下不是上述问题的答案。然而,对于任何来到这里想知道如何合并集合的人(发生在我身上),下面的代码会将一个集合(col2)的内容添加到另一个(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

如果要保留每个集合的内容,请声明一个额外的集合。

Dim super_col As New Collection

addColToCol super_col, col1
addColToCol super_col, col2

加入方法如下:

Join(CollectionToArray(colData), ",")

以及函数:

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

您不需要使用数组。
只需将集合中的每个元素与选定的分隔符连接起来即可。

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