從集合中刪除專案

通過呼叫 .Remove 方法將專案從 Collection 中刪除:

句法:

.Remove(index)
引數 描述
指數 要從 Collection 中刪除的專案。如果傳遞的值是數字型別或帶有數字子型別的 Variant,則它將被解釋為數字索引。如果傳遞的值是包含字串的 StringVariant,則它將被解釋為鍵。如果傳遞了 Collection 中不存在的 String 鍵,則會產生執行時錯誤 5:無效的過程呼叫或引數。如果傳遞的數字索引在 Collection 中不存在,則會產生執行時錯誤 9:下標超出範圍

筆記:

  • Collection 中刪除專案將更改 Collection 中所有專案的數字索引。使用數字索引和刪除專案的 For 迴圈應該向後執行 (Step -1)以防止下標異常和跳過的專案。
  • 通常應該從 For Each 環中移除物品,因為它會產生不可預測的結果。

樣品用法:

Public Sub Example()
    Dim foo As New Collection
    
    With foo
        .Add "One"
        .Add "Two", "Second"
        .Add "Three"
        .Add "Four"
    End With
     
    foo.Remove 1            'Removes the first item.
    foo.Remove "Second"     'Removes the item with key "Second".
    foo.Remove foo.Count    'Removes the last item.
    
    Dim member As Variant
    For Each member In foo
        Debug.Print member  'Prints "Three"
    Next
End Sub