Collection 对象

Collection 对象是一组可称为“单元”的有序项。


使用 Collection 对象,可以非常便捷地将一组相关项引用为一个对象。 只有当集合中的项或成员位于集合中时,它们才必须相互关联。 集合成员无需共用相同的数据类型

集合的创建方式与其他对象相同。 例如:

Dim X As New Collection

在集合创建后,可使用 Add 方法来添加成员,并使用 Remove 方法来删除成员。 若要返回集合中的特定成员,请使用 Item 方法;而若要循环访问整个集合,请使用 For Each...Next 语句。


下面的示例先创建 Collection 对象 (MyClasses),再创建用户可向集合添加对象的对话框。

若要查看其工作原理,请从“插入”菜单中选择“类模块”命令,并在 Class1 的模块级别声明名为 InstanceName 的公共变量, (键入“公共InstanceName) ”以保存每个实例的名称。 Leave the default name as Class1. Copy and paste the following code into the General section of another module, and then start it with the statement ClassNamer in another procedure.


Sub ClassNamer()
    Dim MyClasses As New Collection    ' Create a Collection object.
    Dim Num    ' Counter for individualizing keys.
    Dim Msg As String    ' Variable to hold prompt string.
    Dim TheName, MyObject, NameList    ' Variants to hold information.
        Dim Inst As New Class1    ' Create a new instance of Class1.
        Num = Num + 1    ' Increment Num, then get a name.
        Msg = "Please enter a name for this object." & vbNewLine _
         & "Press Cancel to see names in collection."
        TheName = InputBox(Msg, "Name the Collection Items")
        Inst.InstanceName = TheName    ' Put name in object instance.
        ' If user entered name, add it to the collection.
        If Inst.InstanceName <> "" Then
            ' Add the named object to the collection.
            MyClasses.Add item := Inst, key := CStr(Num)
        End If
        ' Clear the current reference in preparation for next one.
        Set Inst = Nothing
    Loop Until TheName = ""
    For Each MyObject In MyClasses    ' Create list of names.
        NameList = NameList & MyObject.InstanceName & vbNewLine
    Next MyObject
    ' Display the list of names in a message box.
    MsgBox NameList, , "Instance Names In MyClasses Collection"

    For Num = 1 To MyClasses.Count    ' Remove name from the collection.
        MyClasses.Remove 1    ' Since collections are reindexed automatically, remove the first member on each iteration.
End Sub



有关于 Office VBA 或本文档的疑问或反馈? 请参阅 Office VBA 支持和反馈,获取有关如何接收支持和提供反馈的指南。