循环遍历VBA中的所有集合

循环遍历VBA中的所有集合,vba,collections,excel,Vba,Collections,Excel,我有一个在VBA中创建几个不同集合的程序。程序完成后,我需要删除每个集合中的记录。我已经能够使用以下代码静态删除集合: Sub Empty_Collections() Dim Count As Integer Dim i As Long Count = Managers.Count For i = 1 To Count Managers.Remove (Managers.Count) Next i Count = FS.Cou

我有一个在VBA中创建几个不同集合的程序。程序完成后,我需要删除每个集合中的记录。我已经能够使用以下代码静态删除集合:

Sub Empty_Collections()
    Dim Count As Integer
    Dim i As Long

    Count = Managers.Count
    For i = 1 To Count
         Managers.Remove (Managers.Count)
    Next i

    Count = FS.Count
    For i = 1 To Count
         FS.Remove (FS.Count)
    Next i

    Count = Staff.Count
    For i = 1 To Count
         Staff.Remove (Staff.Count)
    Next i

    Count = Clusters.Count

    For i = 1 To Count
         Clusters.Remove (Clusters.Count)
    Next i

End Sub
但是,由于我将来可能会添加其他集合,是否可以使用类似于以下内容的代码:

Dim Item As Collection
Dim Count As Integer
Dim i As Long

For Each Item In Worksheets
    Count = Item.Count

    For i = 1 To Count
         Item.Remove (Item.Count)
    Next i

Next

虽然我对创建这样的全局对象犹豫不决,但这里有一个可能的解决方案:

ThisWorkbook
Excel对象中,添加以下内容:

Private pCollections As Collection
Public Property Get Collections() As Collection
    If pCollections Is Nothing Then: Set pCollections = New Collection
    Set Collections = pCollections
End Property
Public Property Set Collections(Value As Collection)
    Set pCollections = Value
End Property

Public Sub AddCollection(Name As String)
    Dim Coll As New Collection
    Me.Collections.Add Coll, Name
End Sub

Public Sub EmptyCollections()
    Dim Coll As Collection
    For Each Coll In Me.Collections
        EmptyCollection Coll
    Next Coll
End Sub

Private Sub EmptyCollection(ByRef Coll As Collection)
    Do While Coll.Count > 0
        ' Remove items from the end of the collection
        Coll.Remove Coll.Count
    Loop
End Sub
然后添加集合并使用集合,如下所示:

' Add collections
' (without helper)
Dim Managers As New Collection
ThisWorkbook.Collections.Add Managers, "Managers"

' (with helper)
ThisWorkbook.AddCollection "FS"
ThisWorkbook.AddCollection "Staff"
ThisWorkbook.AddCollection "Clusters"

' Add items to collection
' (access collection via named key for ease-of-use)
ThisWorkbook.Collections("Managers").Add "Alice"
ThisWorkbook.Collections("Managers").Add "Bob"

' (or original reference if desired
Managers.Add "Carl"

Debug.Print Managers.Count ' => 3
Debug.Print ThisWorkbook.Collections("Managers").Count ' => 3

' Add collection later
ThisWorkbook.AddCollection "FutureCollection"

' Empty all collections
ThisWorkbook.EmptyCollections

这可能比您要查找的内容要复杂一点,但它的优点是将集合添加到中心位置,以便以后可以清空所有集合。

简单得多(例如)
Set Managers=New Collection
如果您希望能够跟踪所有的集合,那么您可以将它们放在一个集合中。除非我误解了您的操作,否则在程序完成时不需要清理,除非您有循环引用。垃圾收集器应该帮你解决这个问题。Tim在第一条评论中说的另一种方法是:
Set Managers=Nothing