Logo: TechTrax...brought to you by MouseTrax Computing Solutions

Creating a Table of Contents Spanning Multiple Documents

by Jonathan West, MVP

Update, March, 2003!
Jonathan West:
This article code has been updated. It was as a result of feedback and sample files from Colin Tate. It turned out that the macro didn't adequately cope with the following:

  1. I hadn't allowed for the \f switch to be at the end of the field instead of the beginning.
  2. I hadn't fully allowed for the filename to be in quotes.
  3. Colin's documents were set so that even the first section of each document was formatted to continue the page numbering from the previous section—even through there was no previous section to follow on from! Configured that way, the documents wouldn't hold the starting page number assigned to them. I'd never seen documents configured that way, and hadn't allowed for it.

The changes do the following>

  • strip the \f from the end of the field code if present (as well as from the beginning)
  • strip quotes from the filename if present
  • ensure that the first section of each document is configured so that it does restart page numbering

Sometimes it is necessary to have a project which involves creating a very large document or set of documents. Such projects often involve multiple authors, each of whom is responsible for one or more individual chapters.

You end up with the job of putting together a Table of Contents that spans the entire set, and perhaps ensuring that all the page numbers are consecutive. There are a number of possible approaches to this

  1. Creating a TOC for each document, and doing a cut/paste job to put all the TOCs together.
  2. Inserting all the individual chapters into a single document, and then updating the TOC.
  3. Using a Master Document.
  4. Creating the TOC using RD fields.

Option #1 is just a horrible laborious mess and is to be avoided, especially as you'll have to do it all over again when the document is updated.

Option #2 will work okay for documents up to 1000 pages or so, provided that your authors have all based their documents on the same template and have carefully followed your rules regarding styles, etc. If they haven't, then you are faced with the prospect of an awful lot of editing and reformatting to make it all look right when you insert the other documents. Creating the TOC and printing it out is probably the last thing on your list of things to do for delivering the final document. Your authors have probably been late delivering their text, you are up against deadlines, and absolutely the last thing you need is a major reformatting job so that you can deliver the final product!

Option #3 is not to be recommended, for similar reasons as Option #2, and also because Master Documents have tended to be somewhat unstable and prone to corruption. Microsoft introduced Master Documents in Word 6, and have been struggling ever since (for about 10 years) to get the feature right and stable, and have never quite managed it! Take a look at this article by John McGhie, Word MVP, for the gruesome details on Master Documents. "Why Master Documents corrupt".

So, that leaves us with RD fields (Option # 4), which are the oldest and most stable mechanism in Word for this purpose. RD fields have been around at least since Word for Windows 2 and I think were available in Word for Windows 1.

When using RD fields, the normal approach is to have a separate document that contains your cover page for the entire document set, plus the Table of Contents and whatever other introductory material is needed. So, the first thing you do is create that document.

Now, because the cover page document contains no headings, the Table of Contents will probably display the following text. "Error! No table of contents entries found." Do not panic, this is expected.

The next thing that has to be done is to insert the RD fields. Press Alt/F9 to display the field codes in the document. The TOC field will now look something like this.

{ TOC \o "1-3" \h \z }

Now we have to insert the RD fields. The way to do this is to move the cursor to the end of the document, and press Ctr/F9. A fresh pair of empty field braces will be inserted, looking like this { }.

The cursor will already be positioned between the braces ready for you to type the field details. Type in RD \f chapter1.doc, so that the field looks like this

{ RD \f chapter1.doc }

This assumes that the first file you want to reference is called chapter1.doc, and that it is located in the same folder as the cover page document. If your first document has a different name, then set that instead. If there are spaces in the name, e.g. the file is called chapter 1.doc instead of chapter1.doc, then you must put quotation marks round the filename. Make sure that the quotes are not replaced with Smart Quotes when you type them. It should look like this.

{ RD \f "chapter 1.doc" }

If you are using Word 97, you will have to leave out the \f switch. The \f switch specifies that relative pathnames are calculated relative to the location of the document containing the Table of Contents, but this option was only introduced in Word 2000. Don't worry about it, we'll deal with that problem later.

Insert as many RD fields as you need. They must be inserted in the order in which you want them to appear in the Table of Contents. When you have finished, it will look something like this.

{ TOC \o "1-3" \h \z }
{ RD \f Chapter1.doc }
{ RD \f Chapter2.doc }
{ RD \f Chapter3.doc }

Now you are ready to update the Table of Contents. Press Alt/F9 to toggle the field codes. The RD fields will disappear (unless you are displaying hidden text from Tools/Options/View). Position the cursor on the Table of Contents and press F9 to update this field code. The Table of Contents will now contain entries for all the other documents.

Unfortunately, what has probably happened is that the page numbers on each document start at page 1, so the Table of Contents looks a real mess with the page numbers starting afresh at each document. You probably want the pages to be numbered consecutively throughout the document. If the cover page file including the TOC is 5 pages, then you want chapter1.doc to start at page 6.

To do this by hand is cumbersome, but do-able if you don't have too many separate files. Open chapter1.doc, and then go to Insert/Page Numbers. The following dialog will appear.

Image of Page Numbers dialog box.

Click the Format button and the following dialog will appear.

Image of Page Number Format dialog box, which is an extension of the Page Number dialog, showing the option selected to continue from previous section.

Click the Start at button, and enter 6 in the box to the right of it (or whatever you want as your starting page number), and then click OK to close the dialog. The Page Numbers dialog will have changed to that it now looks like this. (Note: The Cancel button is now a Close button.)

Image of the Page Number dialog again, now showing the Cancel button has changed to a Close button.

Click Close to clear the dialog. Don't click OK, as this will insert page numbers into the header. I'm assuming that the page numbers are already there and you don't need another set!

Now you need to move to the end of the document to find out the page number of the last page. Write it down, you will need it in order to set the starting page of the next chapter. Now save and close chapter1.doc.

You then open Chapter2.doc and repeat the whole process, adding 1 to the page number of the last page of current chapter, in order to set the starting page for the next chapter. Once you have been through all the chapters, you can then update the Table of Contents again, and provided you have made no mistakes anywhere, the page numbers in the TOC will all be straightened out.

As you can see, this is a somewhat laborious process if you have more than 2 or 3 documents in the set. Fortunately, this process is an ideal candidate for a bit of automation; and just to make life easier for you, I have written the macro that does this. (The code for this is also in the TechTrax Library, if you want to download it and import it directly into your template.)


Sub UpdateTocAndPageNumbers()
Dim oField As Field
Dim strCode As String
Dim iLastPage As Long
Dim oDoc As Document

ChDir ActiveDocument.Path
With ActiveDocument.ActiveWindow.View
    .ShowAll = False
    .ShowHiddenText = False
    .ShowFieldCodes = False
    .Type = wdPrintView
End With
ActiveDocument.Repaginate
Selection.Move unit:=wdStory, Count:=1
iLastPage = Selection.Information(wdActiveEndAdjustedPageNumber)

For Each oField In ActiveDocument.Fields
    If oField.Type = wdFieldRefDoc Then
        strCode = Trim$(oField.Code)
        strCode = Trim$(Mid$(strCode, InStr(strCode, " ")))
        If LCase$(Left$(strCode, 2)) = "\f" Then
            strCode = Trim$(Mid$(strCode, 3))
        End If
        If LCase$(Right$(strCode, 2)) = "\f" Then
            strCode = Trim$(Left$(strCode, Len(strCode) - 2))
        End If
        If Asc(strCode) = 34 Then
            strCode = Trim$(Mid$(strCode, 2, Len(strCode) - 2))
        End If

        ChDir ActiveDocument.Path
        Set oDoc = Documents.Open(FileName:=strCode)
        oDoc.Activate
        With oDoc.ActiveWindow.View
            .ShowAll = False
            .ShowHiddenText = False
            .ShowFieldCodes = False
            .Type = wdPrintView
        End With
        oDoc.Sections(1).Headers(wdHeaderFooterPrimary). _
                 PageNumbers.RestartNumberingAtSection = True
        oDoc.Sections(1).Headers(wdHeaderFooterPrimary). _
                 PageNumbers.StartingNumber = iLastPage + 1
        oDoc.Repaginate
        Selection.Move unit:=wdStory, Count:=1
        iLastPage = Selection.Information(wdActiveEndAdjustedPageNumber)
        oDoc.Close SaveChanges:=wdSaveChanges
    End If
Next oField
ChDir ActiveDocument.Path
ActiveDocument.Fields.Update
End Sub

You run this macro when your cover page document is open. It does the following:

  1. Sets the document so that hidden text and field codes are not displayed. This makes sure that page numbers displayed on the screen match what will be printed.
  2. Repaginates the cover page document, and finds out the page number of the last page.
  3. Finds each RD field in turn. For each field it does the following:
        a. opens the associated document,
        b. sets the starting page to the appropriate value,
        c. repaginates the document,
        d. finds out the page number of the last page,
        e. saves and closes the document.
  4. When all the RD fields have been processed, it updates the fields in the cover page document, including the Table of Contents.

You may need to run this macro twice, initially. This is because the process of updating the Table of Contents may change the number of pages in the cover page document.

The macro will work even for Word 97, where you don't have the \f switch within the RD fields options. If this is the case, you must have all the documents of the set in the same folder. I'd recommend that you do this, anyway.

The same trick can be used to prepare a consolidated index. For the document that contains the INDEX field, you place the RD fields in the same document, but this time you put the RD fields in front of the INDEX field, so they look like this

{ RD \f Chapter1.doc }
{ RD \f Chapter2.doc }
{ RD \f Chapter3.doc }
{ INDEX }

If the Index is preceded by a heading, then the cover page document should include an RD field for the index file, so that the index heading is included in the Table of Contents. You don't need the same RD field in the index file, as it would then be referencing itself.

Once the documents have all been repaginated using the macro above, you can then open the index document and update the index one final time to make sure the page numbers are correct. Then save and close the document.

Now, there's one last thing that you might need to do in a hurry—print the complete document set, in the correct order of chapters. You can open each document in turn and print it, but there's lots of scope for getting it wrong. Fortunately, this can be automated as well. The following macro will do the job. Make sure your laser printer is well stocked up with paper, and that the cover page document is open, and then run this macro.

Sub PrintMultiFile()
Dim oField As Field
Dim strCode As String
Dim oDoc As Document

ChDir ActiveDocument.Path
ActiveDocument.PrintOut Background:=False

For Each oField In ActiveDocument.Fields
    If oField.Type = wdFieldRefDoc Then
        strCode = Trim$(oField.Code)
        strCode = Trim$(Mid$(strCode, InStr(strCode, " ")))
        If LCase$(Left$(strCode, 2)) = "\f" Then
            strCode = Trim$(Mid$(strCode, 3))
        End If
        If LCase$(Right$(strCode, 2)) = "\f" Then
            strCode = Trim$(Left$(strCode, Len(strCode) - 2))
        End If
        If Asc(strCode) = 34 Then
            strCode = Trim$(Mid$(strCode, 2, Len(strCode) - 2))
        End If
        ChDir ActiveDocument.Path
        Set oDoc = Documents.Open(FileName:=strCode)
        oDoc.PrintOut Background:=False
        oDoc.Close SaveChanges:=wdDoNotSaveChanges
    End If
Next oField
ChDir ActiveDocument.Path
End Sub

By the way, if your printer is capable of printing duplex, make sure that duplex printing is switched off before you run this macro. Each file will start on a fresh sheet of paper; and so, if you are printing duplex, there may be a few blank pages if an individual chapter has an odd number of pages. Print it all non-duplex, and then photocopy onto duplex if needed.

 

 

Go up to the top of this page.
This site powered by the Logical Web Publisher™: Content management by Logical Expressions, Inc.