Using the Words Object

The Words object is a collection that represents all the words in whatever object is specified. For example, ActiveDocument.Words is the collection of all the words in the active document. Other objects that have the Words property are Paragraph, Range, and Selection.

You refer to individual words by using an index number with the Words collection. As I mentioned earlier, however, this doesn't return a "Word" object; there is no such thing in Microsoft Word's VBA universe. Instead, individual words are classified as Range objects (see "Working with the Range Object" earlier in this chapter).

The following statement formats the first word in the active document as bold: ActiveDocument.Words(1).Font.Bold = True

To count the number of words in the specified object, use the Count property: totalWords = Documents("Article.docx").Words.Count

Note, however, that the Words object includes the punctuation and paragraph marks inside the object, which is certainly bizarre behavior, and serves to render the Words.Count property more or less useless. If you want to know the number of real words in an object, use the CountWords function shown in Listing 7.8.

0 0

Post a comment