清除集合中的所有專案
清除 Collection
中所有物品的最簡單方法是簡單地用新的 Collection
替換它,讓舊的物品超出範圍:
Public Sub Example()
Dim foo As New Collection
With foo
.Add "One"
.Add "Two"
.Add "Three"
End With
Debug.Print foo.Count 'Prints 3
Set foo = New Collection
Debug.Print foo.Count 'Prints 0
End Sub
但是,如果對 Collection
有多個引用,則此方法僅為你分配的變數提供空的 Collection
。
Public Sub Example()
Dim foo As New Collection
Dim bar As Collection
With foo
.Add "One"
.Add "Two"
.Add "Three"
End With
Set bar = foo
Set foo = New Collection
Debug.Print foo.Count 'Prints 0
Debug.Print bar.Count 'Prints 3
End Sub
在這種情況下,清除內容的最簡單方法是迴圈遍歷 Collection
中的專案數,並重復刪除最低項:
Public Sub ClearCollection(ByRef container As Collection)
Dim index As Long
For index = 1 To container.Count
container.Remove 1
Next
End Sub