Add Method

Applies To

Collection Object.

Description

Adds a member to a Collection object.

Syntax

object.Add(item, [key], [before], [after])

The Add method syntax has the following object qualifier and named-arguments:

Part Description
object Required. An object expression that evaluates to an object in the Applies To list.
item Required. An expression of any type that specifies the member to add to the collection.
key Optional. A unique string expression that specifies a key string that can be used, instead of a positional index, to access a member of the collection.
before Optional. An expression that specifies a relative position in the collection. The member to be added is placed in the collection before the member identified by the before argument. If a numeric expression, before must be a number from 1 to the value of the collection’s Count property. If a string expression, before must correspond to the key specified when the member being referred to was added to the collection. You can specify before or after positions but not both.
after Optional. An expression that specifies a relative position in the collection. The member to be added is placed in the collection after the member identified by the after argument. If numeric, after must be a number from 1 to the value of the collection’s Count property. If a string, after must correspond to the key specified when the member being referred to was added to the collection. You can specify before or after positions but not both.


Remarks

An error occurs if a value provided for before or after would not return a member of the collection when provided to the Item method as the index. In other words, whether the before or after argument is a string or numeric expression, it must refer to an existing member of the collection.

An error also occurs if a specified key duplicates the key for an existing member of the collection.

See Also

Item Method, Remove Method.

Specifics (Microsoft Access)

Items added to a user-defined collection are automatically indexed. You can refer to an individual item by this index. For example, if you have a collection colThings that contains four objects, you can refer to the third item in the collection with the expression colThings(3).

Note When you add items to a Collection object, they are automatically indexed beginning with the number 1. Therefore, when you enumerate a Collection object, keep in mind that the index begins at 1. This may be different from built-in collections, which usually are indexed beginning with 0.

When you add an object to a user-defined collection, you can specify a custom key for that object in addition to the automatic index. In subsequent references to the object, you can refer to the custom key. For example, you can add an object objMine with the following key.


colThings.Add Item := objMine, key := ("A")

Subsequently you can refer to this particular object in the collection either as colThings(A), or by its numeric index.

Example

This example uses the Add method to add Inst objects (instances of a class called Class1 containing a Public variable InstanceName) to a collection called MyClasses. To see how this works, choose the Class Module command from the Insert menu and declare a public variable called InstanceName at module level of Class1 (type Public InstanceName) to hold the names of each instance. Leave the default name as Class1. Copy and paste the following code into the Form_Load event procedure. (If your host application doesn’t have forms, paste the code at module-level and enclose it in a Sub...End Sub block.)


Dim MyClasses As New Collection    ' Create a Collection object.Num As Integer                ' Counter for individualizing keys.TheName                        ' Holder for names user enters.
    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." & Chr(13) _
         & "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 = NothingUntil TheName = ""

The following example creates a user-defined collection and uses the Add method to add new objects to it. To test this example, create a new form and save it as Form1. In the form’s module, declare a public variable varInstName. Your new user-defined objects will be derived from this form and its module.

You can manipulate individual objects within the collection by calling the methods or setting the properties that you have defined for them. In the module of Form1, enter the following code.


' Declare public variable in Declarations section of form module.varInstName As Variant
Sub ChangeCaption (strCaption As String)
    Me.Visible = True
    Me.Caption = strCaptionSub

This Sub procedure becomes a method that you can perform on your user-defined object, once you have created a new instance of the object.

With these steps completed, enter the following procedure in a standard module. When you run this procedure, it will create new instances of your user-defined object and add them to the collection defined by the Collection object. Then it will display the objects (forms in this case) with their changed captions.


Function MakeCollection()
    ' Create new Collection object using New keyword.
    Dim colFormObjects As New Collection
    ' Declare other variables.
    Dim strObjName As String, strList As String
    Dim strMsg As String, strCRLF As String
    Dim intI As Integer

    strCRLF = Chr(13) & Chr(10)

    ' Create objects and add them to collection.
    Do
        ' Create new instance of user-defined object.
        Dim frmObject As New Form_Form1
        strMsg = ("Please enter a name for this new object." & strCRLF _
            & "Press Cancel to see the items in the collection.")
        ' Get name for this instance of object.
        strObjName = InputBox(strMsg, "Name the collection item:")
        ' Store name in public variable you declared in form module.
        frmObject.varInstName = strObjName
        ' If user entered name, add object to collection.
        If frmObject.varInstName <> "" Then
            colFormObjects.Add Item := frmObject
        End If
        ' Clear object variable so it can be set to next instance.
        Set frmObject = Nothing
    Loop Until strObjName = ""

    ' Enumerate and display items in collection.
    ' Note that items in Collection object are indexed beginning with 1.
    intI = 1
    For Each frmObject In colFormObjects
        strList = strList & frmObject.varInstName & strCRLF
        frmObject.ChangeCaption ("New Form #" & intI)
        intI = intI + 1
    Next frmObject
    ' Display list of object names.
    MsgBox strList, , "Objects in colFormObjects collection"Function