How to find the end of a page in a Word document by using Automation (285599)



The information in this article applies to:

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

This article was previously published under Q285599

SUMMARY

This article describes automatic methods for finding the end of a page in a Microsoft Word document.

MORE INFORMATION

There are two methods that you can use to find the end of a page:
  • You can use the pre-defined bookmark "\page". -or-

  • You can use Word's Browser object to change the insertion point to the browser target wdBrowsePage.
The following samples make use of a test document that spans multiple pages. In the test document, a page may end with a paragraph mark, or a page may wrap to a new page, splitting a paragraph between the two pages. Before starting the steps to build the samples below, create a three-page document in Microsoft Word and save it as C:\ThreePageDocument.doc.

Sample #1: Using a Predefined Bookmark

  1. Start a new Visual Basic Standard EXE project. Form1 is created by default.
  2. Add three command buttons to Form1. Change the captions for Command1, Command2, and Command3 to Use \Page Bookmark Method, Move to Next \Page Bookmark and Quit, respectively.
  3. From the Project menu, click References. Select Microsoft Word 9.0 Object Library, and then click OK. Note For Word 2002, select the Microsoft Word 2002 Object Library. For Microsoft Office Word 2003, select the Microsoft Word 11.0 Object Library.

  4. Copy the following code into the code module of Form1:
    Option Explicit
    Dim oWord As Word.Application
    Dim oDoc As Word.Document
    Dim oRange As Word.Range
    Dim iPageNumber As Integer
    Dim iCount As Integer
    
    Private Sub Command1_Click()
        Set oWord = New Word.Application
        oWord.Visible = True
        iPageNumber = 1     ' Initialize
        Set oDoc = oWord.Documents.Open(FileName:="C:\ThreePagedocument.doc")
        oDoc.Bookmarks("\page").Range.Select     ' \page is internal to Word
        oWord.Selection.Collapse direction:=wdCollapseEnd     ' Position insertion point
        oWord.Selection.MoveLeft Unit:=wdCharacter, Count:=1
        Set oRange = oWord.Selection.Range
        oRange.Text = "*"
        oRange.Collapse direction:=wdCollapseEnd
        oRange.Select
        oWord.Selection.MoveRight Unit:=wdCharacter, Count:=1
        MsgBox "Click OK to close this box, then click the document to see the insertion point", vbMsgBoxSetForeground
    End Sub
    
    Private Sub Command2_Click()
        iPageNumber = iPageNumber + 1  ' Point to next page
        iCount = 2
        oDoc.Bookmarks("\page").Range.Select  ' Word's internal bookmark
        oWord.Selection.Collapse direction:=wdCollapseEnd ' move insertion point
        
        If Asc(oWord.Selection.Characters(1).Text) = 13 Then  ' Is this a paragraph mark?
            ' Assume you're at last paragraph of the last page
            Set oRange = oWord.Selection.Range
            oRange.Text = "*"  ' Show that you're at the end of the page
        Else  ' Not at the end of last paragraph on last page
            oWord.Selection.MoveLeft Unit:=wdCharacter, Count:=2 'Possible Para and Page symbols
            ' Check for Autowrap from one page to the next.
            If Asc(oWord.Selection.Characters(1).Text) <> 13 Then 'it is not a paragraph
                oWord.Selection.MoveUp Unit:=wdLine, Count:=1 ' was autowrapped, so force
                                                              ' current line to next page
                                                              ' if inserted text is to go
                                                              ' on this page
            End If
            Set oRange = oWord.Selection.Range
            oRange.Text = "*"  ' Show that you're at the end of the page
            oRange.Collapse direction:=wdCollapseEnd
            oRange.Select
            oWord.Selection.MoveRight Unit:=wdCharacter, Count:=2 ' past the para and asterisk
        End If
        MsgBox "Dismiss this message, then click the document to see the insertion point.", vbMsgBoxSetForeground
    End Sub
    
    Private Sub Command3_Click()
        If Not (oDoc Is Nothing) Then
            oDoc.Saved = True
            oDoc.Close
            Set oDoc = Nothing
            oWord.Quit (False)
            Set oWord = Nothing
        End If
        Unload Me
    End Sub
    					
  5. Press F5 to start the program.
  6. Click Use \Page Bookmark Method. First, Word starts and opens your ThreePageDocument.doc file. Then a message box appears. Follow the instructions that appear in that box.
  7. For subsequent pages, click Move to Next \Page Bookmark.
  8. To quit Word and terminate the demonstration, click Quit.

Sample #2: Using the Browser Object

The code in this section demonstrates that you can separate the content one page at a time from a multi-page document and copy that content into a new document.
  1. Start a new Visual Basic Standard EXE project. Form1 is added by default.
  2. Add two command buttons to Form1. Change the caption of Command1 to Use Word Browser Method and the caption of Command2 to Quit.
  3. From the Project menu, click References. Select Microsoft Word 9.0 Object Library, and then click OK.NOTE: For Word 2002, select Microsoft Word 2002 Object Library. For Microsoft Office Word 2003, select the Microsoft Word 11.0 Object Library.

  4. Copy the following code into the code module of Form1:
    Option Explicit
    Dim oWord As Word.Application
    Dim oDoc As Word.Document
    Dim oNewDoc As Word.Document
    Dim oRange As Word.Range
    Dim iPageNumber As Integer
    Dim iCount As Integer
    Dim strTestDir As String
    Dim strTestFile As String
    
    Private Sub Command1_Click()
        Command1.Visible = False
        Dim lCurrentStart As Long
        Dim lCurrentEnd As Long
        Dim lDocumentEnd As Long
        Dim lOutputCount As Long
        
        lOutputCount = 0
        
        'Launch Word and make it visible
        Set oWord = CreateObject("Word.Application")
        oWord.Visible = True
        
        'Open the test document
        Set oDoc = oWord.Documents.Open(FileName:="C:\ThreePageDocument.doc")
        
        'Find the beginning end of the document
        oDoc.Select
        lCurrentStart = oWord.Selection.Start
        lCurrentEnd = lCurrentStart
        lDocumentEnd = oWord.Selection.End
        
        'Move the insertion point to the beginning of the document
        oWord.Selection.Collapse wdCollapseStart
        
        Do While (lCurrentEnd < lDocumentEnd)
            'Move the insertion pointer to the bottom of this page
            oWord.Browser.Target = wdBrowsePage
            oWord.Browser.Next
            lCurrentEnd = oWord.Selection.End
            
            'On the last page, the start and end will be the same
            If (lCurrentStart = lCurrentEnd) Then
                lCurrentEnd = lDocumentEnd
            End If
            
            'Capture the Range of the current page
            Set oRange = oDoc.Range(lCurrentStart, lCurrentEnd)
            
            'Create a new document and copy the range to it
            Set oNewDoc = oWord.Documents.Add
            oRange.Copy
            oNewDoc.Range(0, 0).Paste
            
            'Release the Range so we don't leak references
            Set oRange = Nothing
            
            'Save the new document and close it
            oNewDoc.SaveAs FileName:="C:\Result" & lOutputCount & ".doc"
                 ' You can save as another FileFormat. If so, change the
                 '  file extension accordingly.
            oNewDoc.Close
            Set oNewDoc = Nothing
            
            'Increment the output counter so we don't overwrite this file later
            lOutputCount = lOutputCount + 1
            
            'Reset the current start position
            lCurrentStart = oWord.Selection.End
        Loop
    End Sub
    
    Private Sub Command2_Click()
        If Not (oDoc Is Nothing) Then
             oDoc.Saved = True
             oDoc.Close
             Set oDoc = Nothing
             oWord.Quit (False)
             Set oWord = Nothing
        End If
        Unload Me
    End Sub
    					
  5. Press F5 to start the program.
  6. Click Use Word Browser Method.
  7. The code will generate a new Word document for each page in the document. Examine the following documents:

    C:\Result0.doc
    C:\Result1.doc
    C:\Result2.doc



(c) Microsoft Corporation 2001, All Rights Reserved. Contributions by Chris Jensen, Microsoft Corporation.

REFERENCES

For additional information, click the following article numbers to view the articles in the Microsoft Knowledge Base:

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

184974 OFF: How to Use (OLE) Automation with Word


Modification Type:MajorLast Reviewed:3/8/2005
Keywords:kbhowto KB285599