Word 자동화를 사용하여 문서의 각 섹션에 있는 페이지 수를 계산하는 방법

요약

이 문서에서는 Word에서 자동화를 사용하여 문서의 각 섹션에 있는 페이지 수를 결정하는 방법을 설명합니다.

추가 정보

다음 샘플 코드는 C:\Mydoc.doc 저장되는 문서를 사용합니다. 샘플 코드를 테스트하려면 여러 섹션과 여러 페이지가 있는 새 문서를 만들고 C:\Mydoc.doc 저장하거나 코드의 문서 경로를 변경하여 기존 Word 문서 중 하나를 참조합니다.

참고: 샘플 코드는 구역 나누기가 강제로 새 페이지 나누기를 적용하고 각 페이지에 둘 이상의 섹션이 포함되어 있다고 가정합니다. 따라서 샘플 코드를 테스트하기 위해 C:\Mydoc.doc Word 문서를 만드는 동안 구역 나누기를 삽입할 때 다음 페이지를 구역 나누기 유형으로 선택해야 합니다.

Visual Basic 샘플

  1. Visual Basic에서 새 표준 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. 기여: 로리 비 터너, Microsoft Corporation.

참조

자세한 내용은 다음 MSDN(Microsoft Developer Network) 웹 사이트를 참조하세요.

Visual Studio를 사용한 Microsoft Office 개발 https://msdn.microsoft.com/en-us/library/aa188489(office.10).aspx

Microsoft Office 개발자 센터 https://msdn.microsoft.com/office

자세한 내용은 Microsoft 기술 자료의 문서를 참조하세요.

Visual C++ 및 MFC를 사용하여 Microsoft Word를 자동화하여 편지 병합을 수행하는 방법 220911