Inserting Text

If you need to insert text into a document, Word offers several Range object methods. In most cases, you start by inserting a paragraph into the document, which you do by running the InsertParagraphAfter method. For example, the current cursor position is given by the Selection object (which I discuss in detail later). To insert a new paragraph after the current cursor position, you'd use the following statement:


You can also run the InsertParagraphBefore method to insert a paragraph before the specified range, or the InsertParagraph method, which inserts a paragraph that replaces the specified range.

With your new paragraph ready, you can then insert text using the InsertAfter method, which inserts text after the specified range:


Range The Range object after which you want to insert the text. Text The text to insert.

For example, the following statement inserts the current date at beginning of the active document:

ActiveDocument.Range(0, 0).InsertAfter Date

Alternatively, you can use the InsertBefore method, which inserts text before the specified Range:


Range The Range object before which you want to insert the text. Text The text to insert.

One common Word task is to start a new document and then populate it with some kind of repeated text. For example, when I start a new chapter of a book, I create a separate document that holds copies of all the chapter's figures, which I then annotate as I go along. Under each image, I add captions such as Figure 7.1, Figure 7.2, and so on. Rather than insert these numbers by hand, I use a macro that prompts me for the chapter number and the total number of figures I think I'll need. The macro then inserts the figure numbers automatically. Listing 7.5 shows a version of this macro.

0 0

Post a comment