Compartilhar via


Words Collection Object

Word Developer Reference

A collection of words in a selection, range, or document. Each item in the Words collection is a Range object that represents one word. There is no Word object.

Remarks

Use the Words property to return the Words object. The following example displays how many words are currently selected.

Visual Basic for Applications
  MsgBox Selection.Words.Count & " words are selected"

Use Words(Index), where Index is the index number, to return a Range object that represents one word. The index number represents the position of the word in the Words collection. The following example formats the first word in the selection as 24-point italic.

Visual Basic for Applications
  With Selection.Words(1)
    .Italic = True
    .Font.Size = 24
End With

The item in the Words collection includes both the word and the spaces after the word. To remove the trailing spaces, use Visual Basic's RTrim function — for example, RTrim(ActiveDocument.Words(1)). The following example selects the first word (and its trailing spaces) in the active document.

Visual Basic for Applications
  ActiveDocument.Words(1).Select

If the selection is the insertion point and it is immediately followed by a space, Selection.Words(1) refers to the word preceding the selection. If the selection is the insertion point and is immediately followed by a character, Selection.Words(1) refers to the word following the selection.

The Count property for this collection in a document returns the number of items in the main story only. To count items in other stories use the collection with the Range object. Also, the Count property includes punctuation and paragraph marks in the total. If you need a count of the the actual words in a document, use the Word Count dialog box. The following example retrieves the number of words in the active document and assigns the value to the variable numWords.

Visual Basic for Applications
  Set temp = Dialogs(wdDialogToolsWordCount)
' Execute the dialog box to refresh its data.
temp.Execute
numWords = temp.Words
Bb212252.vs_note(en-us,office.12).gif  Note
For more information about calling built-in dialog boxes, see Displaying built-in Word dialog boxes.

The Add method isn't available for the Words collection. Instead, use the InsertAfter method or the InsertBefore method to add text to a Range object. The following example inserts text after the first word in the active document.

Visual Basic for Applications
  ActiveDocument.Range.Words(1).InsertAfter "New text "

See Also