2

我有一个程序,我在 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
4

1 回答 1

0

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

ThisWorkbookExcel 对象中,添加以下内容:

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

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

于 2013-11-19T19:18:00.667 回答