Thursday, November 15, 2012

Adding an Independent Section in Word Using VBA

If you are using .NET, this technique is still applicable.  Here is the code we will be discussing (which is commented enough that you might not need to read anything else):



Code Walk Through

First, we insert a section break which starts a new page.  We need to save the current range.  If there is no selection, the current location is treated as a selection.  If there is text selected, it will get replaced a bit later.  We assign the current selection range to a variable to reference after we have changed the current selection.  Changing the current selection will not change the range referred to by r.  (It will continue to point to the same place in the document as when the assignment was made.)  We now add a new section break—this should normally be done before we modify the current range.  Otherwise, the modifications or additions will simply get pushed onto the next page since the selection is still at the beginning of the additions.  If you were able to add stuff and move the current selection to the end of the new stuff, then you could add the section break without pushing the new stuff forward.

After the second section break is added, we modify the range we saved a reference to, in this case, by adding some text.

If you had a document with nothing but the digits 12 in it and placed the cursor after the 1 but before the 2, after executing this code, page one would have 1 on it, page 2 would have Hello, Word! on it and page 3 would have 2 on it.
Post a Comment