How to automate Word to set and retrieve section header/footer information (269565)



The information in this article applies to:

  • Microsoft Office Word 2003
  • Microsoft Word 2002
  • Microsoft Word 2000
  • Microsoft Visual Basic Professional Edition for Windows 5.0
  • Microsoft Visual Basic Professional Edition for Windows 6.0
  • Microsoft Visual Basic Enterprise Edition for Windows 5.0
  • Microsoft Visual Basic Enterprise Edition for Windows 6.0

This article was previously published under Q269565

SUMMARY

This article illustrates how to Automate Microsoft Word to set and retrieve header and footer text in various sections of a document.

MORE INFORMATION

The sample Automation client first demonstrates how to build sections in a document and add header/footer text to those sections. The document that the sample code creates consists of three sections:
  • The first section contains two pages. In this section, the first page header and footer are different from the second page.
  • The second section contains three pages. In this section, the first page header and footer are different from the other two pages.
  • The third section contains two pages. In this section, the pages all share the same header and footer.
NOTE: Whether or not a section contains different headers or footers for the first page is determined by the DifferentFirstPageHeaderFooter property for the Section object.

The sample Automation client also demonstrates how to retrieve the header and footer information from a document. After opening a document, the client iterates each page in the document and outputs the headers and footers for that page to the debug window. Note that the sample code accounts only for first page headers/footers and primary headers/footers; it does not account for even page headers/footers.

Sample

  1. Create a new Standard EXE Project in Visual Basic. Form1 is created by default.
  2. On the Project menu, click References. Select Microsoft Word 9.0 Object Library for Word 2000 (or Microsoft Word 10.0 Object Library for Word 2002 and Microsoft Word 11.0 Object Library for Word 2003 ), and then click OK.
  3. Add two Command buttons to Form1. Change the caption of Command1 to Create Document, and change the caption of Command2 to Retrieve Headers/Footers.
  4. Add the following code to Form1:
    Option Explicit
    
    Private Sub Command1_Click()
        SetHeadersFooters
    End Sub
    
    Private Sub Command2_Click()
        GetHeadersFooters App.Path & "\mydoc.doc"
    End Sub
    
    
    Sub SetHeadersFooters()
    
        Dim oApp As Word.Application
        Dim oSec As Word.Section
        Dim oDoc As Word.Document
        
        'Create a new document in Word
        Set oApp = New Word.Application
        Set oDoc = oApp.Documents.Add
        
        With oDoc
                
            '=== SECTION 1 ==================================================
            
            'Add two pages to the first section where the first page in the
            'section has different headers and footers than the second page
            Set oSec = .Sections(1)
            oSec.PageSetup.DifferentFirstPageHeaderFooter = True
            oSec.Range.InsertAfter "Text on Page 1 (Section 1)"
            .Range(oSec.Range.End - 1).InsertBreak wdPageBreak
            oSec.Range.InsertAfter "Text on Page 2 (Section 1)"
            
            'Add the headers/footers for the first section (that contains two
            'pages)
            oSec.Headers(wdHeaderFooterFirstPage).Range.Text = _
                  "Page1 -- Section 1 First Page Header"
            oSec.Headers(wdHeaderFooterPrimary).Range.Text = _
                  "Page2 -- Section 1 Primary Header"
            oSec.Footers(wdHeaderFooterFirstPage).Range.Text = _
                  "Page1 -- Section 1 First Page Footer"
            oSec.Footers(wdHeaderFooterPrimary).Range.Text = _
                  "Page2 -- Section 1 Primary Footer"
            
            '=== SECTION 2 ==================================================
            
            'Add a new section containing three pages where the first page in 
            'the section has different headers and footers than the other two
            'pages
            .Range(oSec.Range.End - 1).InsertBreak wdSectionBreakNextPage
            Set oSec = .Sections(2)
            oSec.PageSetup.DifferentFirstPageHeaderFooter = True
            oSec.Range.InsertAfter "Text on Page 3 (Section 2)"
            .Range(oSec.Range.End - 1).InsertBreak wdPageBreak
            oSec.Range.InsertAfter "Text on Page 4 (Section 2)"
            .Range(oSec.Range.End - 1).InsertBreak wdPageBreak
            oSec.Range.InsertAfter "Text on Page 5 (Section 2)"
    
            'Add the headers/footers for the second section (that contains
            'three pages) -- notice that the second and third pages in this 
            'section will contain the primary header/footer
            oSec.Headers(wdHeaderFooterFirstPage).LinkToPrevious = False
            oSec.Headers(wdHeaderFooterFirstPage).Range.Text = _
                  "Page3 -- Section 2 First Page Header"
            oSec.Headers(wdHeaderFooterPrimary).LinkToPrevious = False
            oSec.Headers(wdHeaderFooterPrimary).Range.Text = _
                  "Page4and5 -- Section 2 Primary Header"
            oSec.Footers(wdHeaderFooterFirstPage).LinkToPrevious = False
            oSec.Footers(wdHeaderFooterFirstPage).Range.Text = _
                  "Page3 -- Section 2 First Page Footer"
            oSec.Footers(wdHeaderFooterPrimary).LinkToPrevious = False
            oSec.Footers(wdHeaderFooterPrimary).Range.Text = _
                  "Page4and5 -- Section 2 Primary Footer"
            
            '=== SECTION 3 ==================================================
    
            'Add a new section containing two pages that all have the same
            'header/footer
            .Range(oSec.Range.End - 1).InsertBreak wdSectionBreakNextPage
            Set oSec = .Sections(3)
            oSec.PageSetup.DifferentFirstPageHeaderFooter = False
            oSec.Range.InsertAfter "Text on Page 6 (Section 3)"
            .Range(oSec.Range.End - 1).InsertBreak wdPageBreak
            oSec.Range.InsertAfter "Text on Page 7 (Section 3)"
    
            'Add the headers/footers for the third section (that contains
            ' two pages) 
            oSec.Headers(wdHeaderFooterPrimary).LinkToPrevious = False
            oSec.Headers(wdHeaderFooterPrimary).Range.Text = _
                  "Page6and7 -- Section 3 Primary Header Only"
            oSec.Footers(wdHeaderFooterPrimary).LinkToPrevious = False
            oSec.Footers(wdHeaderFooterPrimary).Range.Text = _
                  "Page6and7 -- Section 3 Primary Footer Only"
             
            'Save the document
            .SaveAs App.Path & "\mydoc.doc"
            
        End With
        
        'Make Word visible to examine the document
        oApp.Visible = True
            
    End Sub
    
    Sub GetHeadersFooters(sFile As String)
    
        Dim oApp As Word.Application
        Dim oDoc As Word.Document
        Dim oSec As Word.Section
        Dim oPageStart As Word.Range
        Dim iPage As Integer, iTotalPages As Integer, iSection As Integer
        Dim sHeader As String, sFooter As String
        
        'Open the document
        Set oApp = New Word.Application
        Set oDoc = oApp.Documents.Open(sFile)
        iTotalPages = oDoc.ComputeStatistics(wdStatisticPages)
    
           
        'Retrieve the headers and footers on each page
        With oDoc
        
            iSection = 0
            
            For iPage = 1 To iTotalPages
                
                'Go to the page represented by the page number iPage and
                'retrieve its section
                Set oPageStart = oDoc.GoTo(What:=wdGoToPage, _
                                           Which:=wdGoToAbsolute, Count:=iPage)
                Set oSec = oPageStart.Sections(1)
                
                'If this is a different section than the one in the previous 
                'iteration and it has a first page header/.footer, then 
                'retrieve the first page header/footer for this section. 
                'Otherwise, retrieve the primary header/footer for this section
                If (iSection < oSec.Index) And _
                   (oSec.PageSetup.DifferentFirstPageHeaderFooter) Then
                    sHeader = oSec.Headers(wdHeaderFooterFirstPage).Range.Text
                    sFooter = oSec.Footers(wdHeaderFooterFirstPage).Range.Text
                Else
                    sHeader = oSec.Headers(wdHeaderFooterPrimary).Range.Text
                    sFooter = oSec.Footers(wdHeaderFooterPrimary).Range.Text
                End If
                
                iSection = oSec.Index
                
                'Display the results in the debug window
                Debug.Print "Page " & iPage & ", Section " & iSection & _
                            ":" & vbCrLf
                Debug.Print "   Header: " & sHeader
                Debug.Print "   Footer: " & sFooter
                
            Next
            
        End With
        
        'Make Word visible to compare the document with the results in the 
        'debug window
        oApp.Visible = True
        
    End Sub
    					
  5. Press the F5 key to run the program.
  6. Click Create Document on the form, and note that the Visual Basic client starts Word and creates the new document. When this process is finished, the document is visible. Examine the document and note the varying headers and footers throughout the document.
  7. Close the new document, and then quit Word.
  8. Click Retrieve Headers/Footers on the form. The Visual Basic client starts Word and retrieves the header/footer text for each page in the document. The results appear in the debug window; compare these results to the document.

REFERENCES

For additional information about additional sample code that demonstrates Automation of Microsoft Word from Visual Basic, click the article numbers below to view the articles in the Microsoft Knowledge Base:

220607 How To Automate Word to Perform Mail Merge from Visual Basic

261999 How To Transfer an ADO Recordset to a Word Table with Automation


Modification Type:MajorLast Reviewed:3/23/2006
Keywords:kbAutomation kbhowto kbProgramming KB269565 kbAudDeveloper