Collection オブジェクト

Collection オブジェクトは、アイテムの順序が指定されたセットであり、1 つの単位として参照できます。

注釈

Collection オブジェクトを使用すると、関連性のあるアイテムのグループを 1 つのオブジェクトとして簡単に参照できます。 コレクション内のアイテムつまりメンバーは、コレクションに存在するという事実のみによって関連付けられる必要があります。 コレクションのメンバーは同じデータ型を共有する必要はありません。

コレクションは他のオブジェクトと同じ方法で作成できます。 例:

Dim X As New Collection

コレクションを作成した後、 Add メソッドを使用してメンバーを追加し、 Remove メソッドを使用して削除できます。 特定のメンバーは Item メソッドを使用してコレクションから返すことができますが、コレクション全体は For Each..を使用して反復処理できます。次の ステートメント。

次の使用例は、 Collection オブジェクト (MyClasses) を作成し、ユーザーがコレクションにオブジェクトを追加できるダイアログ ボックスを作成します。

このしくみを確認するには、[挿入] メニューから [クラス モジュール] コマンドを選択し、クラス 1 のモジュール レベルで呼び出されるInstanceNameパブリック変数 (「Public」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.

(This example only works with host applications that support 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 のサポートおよびフィードバックを参照してください。