Collection Add Method

Named Arguments

Syntax objectvariable.Add item [, key, before, after] objectvariable Use: Required

Data Type: Collection object

The name of the Collection object to which an item is to be added.

item

Use: Required

Data Type: Any

An expression of any type that specifies the member to add to the collection.

Use: Optional Data Type: String

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

Use: Optional

Data Type: String or Numeric

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.

after

Key: Optional

Data Type: String or Numeric

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.

Description

Adds a data item to a collection. Rules at a Glance

• If you don't specify a before or after value, the member is appended to the end of the collection.

• If you don't specify a key value, you can't then access this member using a key, but instead must access it either by using its ordinal number or by enu-

Collection.Add Method 167

merating all the members of the collection with the For Each...Next construct.

• Whether the before or after argument is a string expression or a numeric expression, it must refer to an existing member of the collection, or an error (runtime error 5, "Invalid procedure call or argument") occurs. If it's a string value, the key must exist; if numeric it must be between 1 and the maximum number of items.

• Key values must be unique or an error (runtime error 457, "This key is already associated with an element of this collection") is generated.

• You can specify a before or an after position, but not both. Example colMyCollection.Add Item:="Paul Lomax" Key:="Name" Programming Tips & Gotchas

• Using named parameters helps to self-document your code:

colMyCollection.Add Item:="VB and VBA in a Nutshell"_ Key:="Title"

• If your key parameter is a value being brought in from outside your program, you must ensure that each value is always unique. One method for doing this is illustrated in the entry for the Collection.Item method.

See Also

Collection Object, Collection.Count Property, Collection.Item Method, Collection.Remove Method

Was this article helpful?

0 0

Post a comment