MS-Excel / General Formatting

Working with Object Collections

A collection is a set of similar objects. For example, Word's Documents collection is the set of all the open Document objects. Similarly, the Paragraphs collection is the set of all Paragraph objects in a document. Collections are objects, too, so they have their own properties and methods, and you can use these properties and methods to manipulate one or more objects in the collection.

The members of a collection are called the elements of the collection. You can refer to individual elements by either the object's name or an index. For example, the following statement closes a document named Budget.doc:

Documents("Budget.doc").Close

On the other hand, if the Budget.doc document was the first document opened in the current Word session, then you could also use its index value in the following statement to close the document:

Documents(1).Close

If you don't specify an element, VBA assumes you want to work with the entire collection.

Note:It's important to understand that you often can't refer to objects by themselves. Instead, you must refer to the object as an element in a collection. For example, when referring to the Budget.doc document, you can't just use Budget.doc.You have to use Documents("Budget.doc") or Documents(1) (or whatever the correct index is) so that VBA knows you're talking about a currently open document.

[Previous] [Contents] [Next]