|


Here’s a quick tip about the use of a little known
Word.Range property called FormattedText.
If you’ve worked with Word VBA, you’re familiar with the
Word.Range object, the basic text building block. Ranges are used continually
in Word VBA to work with contiguous ranges of text in Word documents. For the
purposes of this article, we assume you’re already familiar with the use of
Ranges.
One common task in Word VBA is to move or copy ranges of text from
one area of a document to another, or from one document to another document.
When using Word, you’d typically accomplish this by using Copy (or Cut) followed by
Paste. When you move to Word VBA, the obvious thing to do is to use the Copy
and Paste methods of the Range object.
For example, to copy the 3rd paragraph to the
current selection using Word VBA, you might run the following code:
Sub Copy3rdParagraphToSelection()
ActiveDocument.Paragraphs(3).Range.Copy
Selection.Paste
End Sub
This code replaces the Selection with the contents of the 3rd
paragraph in the active document. If the Selection is collapsed, it inserts a
copy of the 3rd paragraph at the insertion point. This method uses
the clipboard as an interim storage place for the text.
However, there is a little-known property of the Range
object called FormattedText that can simplify your code and avoid the use of
the clipboard. We could rewrite the code of the function above as a single line
if we use the FormattedText property:
Sub Copy3rdParagraphToSelectionUsingFormattedText()
Selection.FormattedText = ActiveDocument.Paragraphs(3).Range.FormattedText
End Sub
Here’s another example. To copy the contents of the
Selection into a new document, you could use the following code:
Sub CopySelectionToNewDocument()
Selection.Copy
Documents.Add.Content.Paste
End Sub
However, you might find the following code simpler and more
direct:
Sub CopySelectionToNewDocumentUsingFormattedText()
Documents.Add.Content.FormattedText = Selection.FormattedText
End Sub
The FormattedText property can be used with Ranges,
Bookmarks, and the Selection object. To use the FormattedText property with a
Bookmark, you must refer to the bookmark’s Range property, as in
myBookmark.Range.FormattedText.
Using the FormattedText property saves some effort in
dealing with multiple Range objects and using the clipboard. You might not want
the contents of the user’s clipboard modified just to run your code, especially
if you’ve copied large portions of the document to the clipboard. The
FormattedText property avoids the use of the clipboard entirely.

|