Collection 物件

Collection物件是一組可稱為單位的已排序專案。

註解

Collection物件提供便利的方式,將相關的專案群組視為單一物件。 集合中的專案或 成員只需要與它們存在於 集合中的事實相關。 集合的成員不需要共用相同的 資料類型

建立集合的方式與其他物件的建立方式相同。 例如:

Dim X As New Collection

建立集合之後,可以使用 Add 方法新增成員,並使用 Remove 方法移 除成員。 您可以使用 Item 方法從集合傳回特定成員,而整個集合則可以使用 For Each... 來逐一查看。下一個 語句。

範例

本範例會建立 Collection 物件 (MyClasses) ,然後建立一個對話方塊,讓使用者可以在其中將物件新增至集合。

若要查看其運作方式,請從 [插入] 功能表中選擇 [類別模組] 命令,然後在 Class1 的模組層級宣告名為 InstanceName 的公用變數 (類型PublicInstanceName) 以保存每個實例的名稱。 將預設名稱保留為 Class1。 將下列程式碼複製並貼到另一個模組的 [一般] 區段中,然後在另一個程式中使用 語句 ClassNamer 加以啟動。

(此範例僅適用于支援 classes.) 的主應用程式

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.
    Do
        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.
    Next
End Sub

另請參閱

支援和意見反應

有關於 Office VBA 或這份文件的問題或意見反應嗎? 如需取得支援服務並提供意見反應的相關指導,請參閱 Office VBA 支援與意見反應