The following sample code uses a document that is saved to
C:\Mydoc.doc. For testing the sample code, either create a new document with
multiple sections and multiple pages and save it as C:\Mydoc.doc, or change the
document path in the code to reference one of your existing Word
NOTE: The sample code assumes that a section break forces a new page
break and that each page contains no more than one section. Therefore, when you
insert section breaks while creating the C:\Mydoc.doc Word document for testing
the sample code, you should choose Next Page as the Section Break type.
Visual Basic Sample
In Visual Basic, create a new Standard EXE project. Form1
is created by default.
Add a command button to Form1, and add the following code
to the button's Click event:
Dim oApp As Object
Dim oDoc As Object
Dim oTbl As Object
'Start Word and open the document.
Set oApp = CreateObject("Word.Application")
'For Word 2007, change the path to "c:\mydoc.docx"
Set oDoc = oApp.Documents.Open("c:\mydoc.doc")
'Repaginate the document.
'Iterate each section in the document to retrieve the end page of the
'document and compute the page count in that section. The results are
'displayed in the Immediate window.
Dim oSec As Object
Dim nStartPg As Integer, nEndPg As Integer, nSecPages As Integer
Dim NumSections As Integer
NumSections = oDoc.Sections.Count
nStartPg = 1
For Each oSec In oDoc.Sections
nEndPg = oSec.Range.Information(3) - 1 'wdActiveEndPageNumber=3
'Account for the last page.
If oSec.Index = NumSections Then nEndPg = nEndPg + 1
nSecPages = nEndPg - nStartPg + 1
Debug.Print "Section " & oSec.Index & " --", _
"StartPage: " & nStartPg, _
"EndPage: " & nEndPg, _
"TotalPages: " & nSecPages
nStartPg = nEndPg + 1
'Close the document without saving changes and quit Word.
Press F5 to run the application, and click the button on
the form. The code displays the page count for each section in the Immediate
Follow steps 1 through 12 in the following article in the
Microsoft Knowledge Base to create a sample project that uses the IDispatch interfaces and member functions that are defined in the
MSWord9.olb type library: