You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何计算Word文档单页字数?求自动添加页脚字数的VB代码

Word单页字数自动统计并插入页脚的VBA代码

以下代码可自动计算Word文档每一页的字数,并将结果插入对应页面的页脚:

Sub AddPageWordCountToFooter()
    Dim doc As Document
    Dim sec As Section
    Dim rng As Range
    Dim pageNum As Integer
    Dim wordCount As Integer
    
    Set doc = ActiveDocument
    Application.ScreenUpdating = False ' 关闭屏幕更新提速
    
    For Each sec In doc.Sections
        For pageNum = 1 To sec.Range.Information(wdNumberOfPagesInSection)
            ' 定位当前页内容范围
            Set rng = doc.GoTo(What:=wdGoToPage, Name:=pageNum).GoTo(What:=wdGoToBookmark, Name:="\page")
            ' 统计当前页字数(含标点)
            wordCount = rng.Words.Count
            
            ' 定位到当前页的主页脚
            Set rng = sec.Footers(wdHeaderFooterPrimary).Range
            rng.Delete ' 清除原有页脚内容(可选)
            ' 插入自定义格式的字数信息
            rng.Text = "第 " & pageNum & " 页 | 字数:" & wordCount
        Next pageNum
    Next sec
    
    Application.ScreenUpdating = True
    MsgBox "单页字数已更新至页脚", vbInformation
End Sub

使用步骤

  • 打开目标Word文档,按 Alt + F11 打开VBA编辑器
  • 右键点击左侧项目栏中的文档名称 → 插入 → 模块
  • 将上述代码粘贴到模块窗口,按 F5 运行,或回到Word界面通过「开发工具→宏」选择对应宏执行

自定义说明

  1. 保留原有页脚内容:若不想覆盖原有页脚,删除rng.Delete,添加rng.Collapse wdCollapseEnd,在原有内容后追加字数信息
  2. 纯内容字数统计(不含标点):替换原统计逻辑,添加以下代码:
    ' 替换原wordCount = rng.Words.Count这一行
    wordCount = 0
    Dim wd As Range
    For Each wd In rng.Words
        If Trim(wd.Text) <> "" And Not IsPunctuation(wd.Text) Then
            wordCount = wordCount + 1
        End If
    Next wd
    
    同时添加辅助判断函数:
    Function IsPunctuation(str As String) As Boolean
        Dim punctuations As String
        punctuations = ".,;:!?""''()[]{}<>/\-_=+`~@#$%^&*" & Chr(13) & Chr(10) & Chr(9)
        IsPunctuation = InStr(punctuations, str) > 0
    End Function
    
  3. 多节文档适配:代码会自动遍历文档所有节的页面,无需额外修改

内容的提问来源于stack exchange,提问作者sakiasi baleiwai komai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 21:30:43