2012-11-14 90 views
2

我有一个程序,我在VBA中创建了几个不同的集合。程序完成后,我需要删除每个集合中的记录。我已经能够用下面的代码静态地删除集合:循环遍历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 
+3

更容易做(例如)'Set Managers = New Collection' –

+4

如果你想能够跟踪所有的收藏,那么你可以随时把它们放在一个集合中。 –

+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 

这可能是一个小比你在找什么更复杂,但它加入集合到一个中心位置的优势,使他们能够全部在稍后清空。