如何使用 Word 自动化计算文档每一节的页数
下面的示例代码使用保存到 C:\Mydoc.doc 的文档。为了测试该示例代码,新建一个包含多节和多页的文档,然后将其另存为 C:\Mydoc.doc,或者更改代码中的文档路径以引用某个现有 Word 文档。
注意:该示例代码假定一个分节符强制生成一个新的分页符,并且每个页面中包含的节数不多于一个。因此,如果在创建用于测试示例代码的 C:\Mydoc.doc Word 文档时插入分节符,则应选择下一页作为分节符类型。
注意:该示例代码假定一个分节符强制生成一个新的分页符,并且每个页面中包含的节数不多于一个。因此,如果在创建用于测试示例代码的 C:\Mydoc.doc Word 文档时插入分节符,则应选择下一页作为分节符类型。
Visual Basic 示例
- 在 Visual Basic 中,新建一个标准 EXE 项目。默认情况下会创建 Form1。
- 向 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
- 按 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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理