• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

gisoracle

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

如何使用 Word 自动化计算文档每一节的页数

下面的示例代码使用保存到 C:\Mydoc.doc 的文档。为了测试该示例代码,新建一个包含多节和多页的文档,然后将其另存为 C:\Mydoc.doc,或者更改代码中的文档路径以引用某个
下面的示例代码使用保存到 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")
        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 示例

================================

Private Sub CommandButton1_Click()
     
      Dim oSec As Object
    Dim nStartPg As Integer, nEndPg As Integer, nSecPages As Integer
    Dim NumSections As Integer
    NumSections = ActiveDocument.Sections.Count
    nStartPg = 1

        For Each oSec In ActiveDocument.Sections
        nEndPg = oSec.Range.Information(3)   'wdActiveEndPageNumber=3
       'Account for the last page.
       If oSec.Index = NumSections Then nEndPg = nEndPg
       nSecPages = nEndPg - nStartPg + 1
       MsgBox "第 " & oSec.Index & "节 ," & "开始页面: " & nStartPg & ",结束页面: " & nEndPg & "总的: " & nSecPages
       nStartPg = nEndPg + 1

        Next

End Sub

 

posted on 2009-09-08 20:52  gisai  阅读(1589)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3