将项添加到集合中

通过调用 .Add 方法将项添加到 Collection

句法:

.Add(item, [key], [before, after])
参数 描述
项目 要存放在 Collection 中的项目。这基本上可以是赋值变量的任何值,包括基本类型,数组,对象和 Nothing
可选的。String 作为从 Collection 中检索项目的唯一标识符。如果指定的密钥已经存在于 Collection 中,则将导致运行时错误 457:此密钥已与此集合的元素相关联
之前 可选的。用于在 Collection 之前插入项目的现有密钥(String 值) 索引(数值)。如果给出了值,则 after 参数必须为空,否则将导致运行时错误 5:无效的过程调用或参数。如果传递了 Collection 中不存在的 String 密钥,则会产生运行时错误 5:无效的过程调用或参数。如果传递的数字索引在 Collection 中不存在,则会产生运行时错误 9:下标超出范围
可选的。用于在 Collection 之后插入项目的现有密钥(String 值) 索引(数值)。如果给定值,则 before 参数必须为空。引发的错误与 before 参数相同。

笔记:

  • 密钥区分大小写。.Add "Bar", "Foo".Add "Baz", "foo" 将导致键碰撞。

  • 如果没有给出可选的 beforeafter 参数,则该项目将添加到 Collection 中的最后一项之后。

  • 通过指定 beforeafter 参数进行的插入将改变现有成员的数字索引以匹配其新位置。这意味着在使用数字索引在循环中进行插入时应该小心。

样品用法:

Public Sub Example()
    Dim foo As New Collection
    
    With foo
        .Add "One"            'No key. This item can only be retrieved by index.
        .Add "Two", "Second"  'Key given. Can be retrieved by key or index.
        .Add "Three", , 1     'Inserted at the start of the collection.
        .Add "Four", , , 1    'Inserted at index 2.
    End With
    
    Dim member As Variant
    For Each member In foo
        Debug.Print member    'Prints "Three, Four, One, Two"
    Next
End Sub