Export (0) Print
Expand All
Expand Minimize
1 out of 6 rated this helpful - Rate this topic

Office Space: Tips and Tricks for Scripting Microsoft Office Applications

Office Space

Welcome to Office Space, the new column that offers tips and tricks for scripting Microsoft® Office applications. We’ll post new tips every Tuesday and Thursday; to see an archive of previous tips, visit the Office Space Archive. And if you have particular questions about Microsoft Office scripting, feel free to send them to scripter@microsoft.com (in English, if possible). We can’t promise to answer all the questions we receive, but we’ll do our best.

Inserting a Page Break in a Word Document

Now that you’ve begun using Microsoft Word as a way to create slick-looking system administration reports, you’ve probably encountered a problem: how the heck do you insert a page break into a report? For example, you might have a script that gathers information from all your domain controllers and then saves that information to a Word document. You’d like the information for domain controller A to appear on page 1 and the information for domain controller B to appear on page 2. That means you need to insert a page break in your document. How hard is that going to be?

Relax: it’s not going to be hard at all. Here’s a script that creates a new Word document, types This is page 1, inserts a page break, and then types This is page 2 on the second page of the document:



Const wdPageBreak = 7 

Set objWord = CreateObject("Word.Application")
objWord.Visible = TRUE
Set objDoc = objWord.Documents.Add()

Set objSelection = objWord.Selection

objSelection.TypeText "This is page 1"
objSelection.InsertBreak(wdPageBreak)
objSelection.TypeText "This is page 2"



We told you it was easy. We begin by creating a constant named wdPageBreak and assigning it the value 7; this will instruct our script to insert a page break as opposed to, say, a column break or a text-wrapping break. We then create an instance of Word, set the Visible property to TRUE (just so you can see what the script is doing), and then create a new document. We create an instance of the Selection object and then type in our first bit of text using this line of code:



objSelection.TypeText "This is page 1"



Now comes the exciting part: the moment when we actually insert a page break! As you can see all we need to do is call the InsertBreak method, passing as the sole parameter the constant wdPageBreak:



objSelection.InsertBreak(wdPageBreak)



And then, just to prove it worked, we type some more text. Take a look at the document, and you’ll see This is page 1 on page 1 and This is page 2 on page 2. Just the way you wanted!

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.