循环遍历VBA中的所有集合

时间:2012-11-14 23:29:53

标签: vba collections excel-vba 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.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

1 个答案:

答案 0 :(得分:0)

虽然我犹豫要创建这样的全局变量,但这是一个可能的解决方案:

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

这可能比你想要的要复杂得多,但它的优点是可以将集合添加到一个中心位置,以便以后可以清空它们。