Creating Collections of Objects


 
Collections are objects themselves. The first step in creating a collection of objects is to create the Collection object itself. Once the Collection object is created, items can be added, removed, and otherwise manipulated through it. In this example, you learn how to create and populate a Collection object.

To create a collection

  1. Declare and instantiate a Collection variable as shown in the sample code below:

    Dim myCollection As New Collection()
     
  2. Use the Add method to add members to your collection. In this example, you create four strings and add them to your collection. A unique String value may optionally be added as the key for the members of your collection. This value is passed to the collection as the second argument of the Add method.

    Dim w, x, y, z As String
    w = "Wow!"
    x = "It's"
    y = "A"
    z = "Collection"
    myCollection.Add(w, "This")
    myCollection.Add(x, "Is")
    myCollection.Add(y, "A")
    myCollection.Add(z, "Key")
     
  3. If you want to remove any members of your collection, you can use the Remove method to do so based either on the index of the member, or on the optional key. Examples are shown below:

    myCollection.Remove(1)   ' Removes the first member of the collection.
    myCollection.Remove("Is")   ' Removes the member with the key "Is".

    Note that when a member is removed from a collection, the index values are renumbered from one to the Count value.

You can use the For Each...Next statement to loop through and process the members of your collection, as in the continuation of our example below.

To use For Each...Next to process the members of your collection

  1. Declare a variable of the type you want to process in your collection. For example, if you want to loop through all your strings, declare a variable of type String, as shown below:
     
  2. Use the For Each...Next statement to examine each member of your collection. In this example, you search for a particular string, and if you find it, display it in a message box.

    For Each aString in myCollection
       If aString = "Collection" Then
          MsgBox(aString)   ' Displays "Collection".
       End If
    Next