The Words Object

     

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 "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.doc").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.5.

Listing 7.5. A Function that Counts the Number of "Real" Words in an Object, Ignoring Punctuation Marks and Paragraph Marks
 Function CountWords(countObject As Object) As Long     Dim i As Long, word As Range     i = 0     For Each word In countObject.Words         Select Case Asc(Left(word, 1))             Case 48 To 57, 65 To 90, 97 To 122                 i = i + 1         End Select     Next 'word     CountWords = i End Function Sub TestCountWords()     With ActiveDocument         MsgBox "Words.Count reports " & .Words.Count & Chr(13) & _                "CountWords reports " & CountWords(.Range)     End With End Sub 

This function takes a generic object as an argument (because the function can work with a Document , Range , or Selection object). It then uses a For Each loop to run through each word in the object. With each loop, the ASCII value of the leftmost character is plugged into a Select Case statement. If that value is between 48 and 57, between 65 and 90, or between 97 and 122, it means the character is either a number or a letter. If so, the function counts the word as a "real" word and increments the counter i.



Absolute Beginner's Guide to VBA
Absolute Beginners Guide to VBA
ISBN: 0789730766
EAN: 2147483647
Year: 2003
Pages: 146

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net