Collection.Item Method

Named Arguments

Yes

Syntax

objectvariable.Item(index)

objectvariable

Use: Required

Data Type: Collection object

An object variable of type Collection.

index

Use: Required

Data Type: Numeric or String

If a string, index is the key; if numeric, index is the ordinal position.

Description

Returns the member of the collection whose key or ordinal position corresponds to index.

Rules at a Glance

  • If index is a string, it's taken to be the key, and the member of the collection with the key of index is returned.

  • If index is a number, it's taken to be the index number and the member in the ordinal position index is returned.

  • If index is a string and the key doesn't exist in the collection, an error (run-time error 5, "Invalid procedure call or argument") is generated.

  • If index is numeric, it must be between 1 and the maximum number of items in the collection, or an error (runtime error 9, "Subscript out of range") is generated.

Programming Tips and Gotchas

  • When writing wrapper classes for collections, you can make your object model more readable by making the name of the property that wraps the Item method the same as the name of the object being obtained from the collection. For example, if your collection class is called Employees and is a collection of Employee records, your object model reads much better with an Employee Property Get procedure, as follows:

    Public Property Get Employee(vEmpCode as Variant) _ As Boolean Employee = mcolEmployees.Item(vEmpCode) End ...

Get VB & VBA in a Nutshell: The Language now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.