O'Reilly logo

Writing Word Macros, Second Edition by Steven Roman PhD

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Example: Printing Document Headings

Having concluded our survey of the Document object and its children, we can now take a look at several sample programs that use them. The first of these is a routine that prints document headings.

As you probably know, Microsoft Word has an outline view that is designed to provide an overview of a Word document by showing only the document headings (and optionally some text). I find the outline view to be of limited use, especially since I have had trouble getting it to display just Heading styles. (For some reason, it seems to want to display some custom styles despite my best efforts to display only Heading styles.)

In any case, the macro in Example 12-6 creates a new document that contains only the headings from the active document. More specifically, the macro first asks the user for a number, X. Then it creates a new Word document and inserts into this document those paragraphs in the active document that have style Heading 1 through Heading X.

There are a couple of points to observe when looking at this code. First, I use the Like operator:

	If para.Format.Style Like "Heading [0-9]" Then

to select styles of the form Heading X, where X is any single digit.

Second, the For Each loop must check each paragraph in the document, which can take some time for a large document (at least several seconds). The first statement within this For Each loop is:

	DoEvents

which tells VBA to allow Windows to perform any normal windows housekeeping while the loop is ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required