Word オートメーションを使用してドキュメントの各セクションのページ数をカウントする方法

概要

この記事では、Word でオートメーションを使用して、ドキュメントの各セクションのページ数を決定する方法について説明します。

詳細情報

次のサンプル コードでは、C:\Mydoc.docに保存されるドキュメントを使用します。サンプル コードをテストするには、複数のセクションと複数のページを含む新しいドキュメントを作成してC:\Mydoc.docとして保存するか、コード内のドキュメント パスを変更して既存の Word 文書のいずれかを参照します。

注: サンプル コードでは、セクション区切りによって新しい改ページが強制され、各ページに含まれるセクションが 1 つ以下であることを前提としています。 そのため、サンプル コードをテストするためのC:\Mydoc.doc Word 文書の作成時にセクション区切りを挿入する場合は、セクション区切りの種類として [次のページ] を選択する必要があります。

Visual Basic サンプル

  1. Visual Basic で、新しい Standard EXE プロジェクトを作成します。 Form1 は既定で作成されます。

  2. Form1 にコマンド ボタンを追加し、ボタンの Click イベントに次のコードを追加します。

        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.
        oDoc.Repaginate
    
    '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
        Next
    
    'Close the document without saving changes and quit Word.
        oDoc.Close False
        oApp.Quit
    
    
  3. F5 キーを押してアプリケーションを実行し、フォームのボタンをクリックします。 このコードでは、イミディエイト ウィンドウに各セクションのページ数が表示されます。

MFC サンプル

  1. MICROSOFT サポート技術情報の次の記事の手順 1 ~ 12 に従って、MSWord9.olb タイプ ライブラリで定義されている IDispatch インターフェイスとメンバー関数を使用するサンプル プロジェクトを作成します。

  2. Excel オートメーション ライブラリを削除する必要があります。

    AutoProjectDlg.cpp の上部に、次のいずれかの行を追加します。

    • Word 2002 以降のバージョンの Word では、次の行を追加します。

      #include "MSWord.h"
      
    • Word 2000 で、次の行を追加します。

      #include "MSWord9.h"
      
  3. AutoProjectDlg.cpp の CAutoProjectDlg::OnRun() に次のコードを追加します。

    COleVariant vOpt((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
    
    //Start Word.
    _Application oWord;
    oWord.CreateDispatch("Word.Application");
    oWord.SetScreenUpdating(FALSE);
    
    //Open the document.
    Documents oDocs = oWord.GetDocuments();
    // For Word 2007, use:
    // _Document oDoc = oDocs.Open(COleVariant("c:\\mydoc.docx"),
    //     vOpt,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt, vOpt, vOpt,vOpt,vOpt,vOpt,vOpt);
    _Document oDoc = oDocs.Open(COleVariant("c:\\mydoc.doc"),
             vOpt,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt, vOpt, vOpt,vOpt,vOpt,vOpt,vOpt);
    
    //Repaginate the document.
    oDoc.Repaginate();
    
    //Iterate the collection of sections in the document to retrieve the page 
    //count for each section.
    Sections oSecs = oDoc.GetSections();
    long NumSections = oSecs.GetCount();
    long i;
    long StartPage=1; //Section start page.
    long EndPage=0;  //Section end page.
    long NumPages=0;  //Number of pages in the section.
    for(i=1;i<=NumSections;i++)
    {
    Section oSec = oSecs.Item(i);
    Range oSecRange = oSec.GetRange();
    VARIANT vInfo = oSecRange.GetInformation(3L);//wdActiveEndPageNumber=3
    //If oSec.Index = NumSections Then nEndPg = nEndPg + 1
    if(oSec.GetIndex()== NumSections) {EndPage++;}
    EndPage = vInfo.lVal-1;
    if(i==NumSections) {EndPage++;}  //Account for the last section.
    NumPages = EndPage - StartPage +1;
    char buf[5];
    sprintf(buf,"%d", NumPages);
    TRACE1("Section %d\n", oSec.GetIndex());
    TRACE3("   StartPage: %d  EndPage: %d   TotalPages: %d\n",
       StartPage, EndPage, NumPages);
    StartPage = EndPage + 1;
    }
    
    //Close the document without saving the changes, and then exit Word.
    oDoc.Close(COleVariant((short)false), vOpt, vOpt);
    oWord.Quit(COleVariant((short)false), vOpt, vOpt);
    
    
  4. プロジェクトをコンパイルして、実行します。

  5. ダイアログ ボックスが表示されたら、[ 実行] をクリックします。 カウント結果は、[デバッグ] ウィンドウに表示されます。 NumPages 変数を [デバッグ] ウィンドウにドラッグする必要があります。

(c) Microsoft Corporation 2001、All Rights reserved。 Lori B. Turner(Microsoft Corporation) による寄稿。

関連情報

詳細については、次の Microsoft Developer Network (MSDN) Web サイトを参照してください。

Visual Studio を使用した Microsoft Office Development https://msdn.microsoft.com/en-us/library/aa188489(office.10).aspx

Microsoft Office デベロッパー センター https://msdn.microsoft.com/office

詳細については、Microsoft サポート技術情報の記事を参照してください。

220911 Visual C++ と MFC を使用して Microsoft Word を自動化して差し込み印刷を実行する方法