【问题标题】:Looping through All collections in VBA循环遍历 VBA 中的所有集合
【发布时间】:2012-11-03 13:29:24
【问题描述】:

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

【问题讨论】:

  • 更容易做到(例如)Set Managers = New Collection
  • 如果您希望能够跟踪所有收藏,那么您可以随时将它们放在一个收藏中。
  • 除非我误解了你在做什么,除非你有循环引用,否则程序完成时应该不需要清理。垃圾收集器应该为你处理好这些。
  • Tim 在第一条评论中所说的另一种方式:Set Managers = Nothing

标签: vba collections excel


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2016-07-16
    • 1970-01-01
    • 1970-01-01
    • 2014-02-05
    • 1970-01-01
    • 2018-06-16
    • 2014-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多