Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
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 a before position or an after position, 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 referred to was added to the collection. You can specify a before position or an after position, but not both. |
Remarks
Whether the before or after argument is a string expression or numeric expression, it must refer to an existing member of the collection, or an error occurs.
An error also occurs if a specified key duplicates the key for an existing member of the collection.
Example
This example uses the Add method to add strings to a collection both with and without a key. The Item method is used implicitly to retrieve each string.
Dim c As Collection
Set c = New Collection
c.Add "a"
c.Add "c", "CC"
c.Add "b", "BB", 2
c.Add "d"
Debug.Print c(1) ' --> prints "a"
Debug.Print c(2) ' --> prints "b"
Debug.Print c(3) ' --> prints "c"
Debug.Print c("BB") ' --> prints "b"
Debug.Print c("d") ' --> error (no key was specified for this element - a positional index must be used)
See also
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.