通过宏来修改Word中自动目录中的页码格式
Word中,由引用生成的目录中,如果标题中包含数字,那么就不能简单地通过查找替换来实现修改为特定的页码格式.
此时,可以考虑通过vba查找域代码 (field code)
Sub AddDiXPageToToc()
Dim toc As TableOfContents
Dim f As Field
Dim startPos As Long, endPos As Long
Dim starts As New Collection
Dim ends As New Collection
Dim i As Long
If ActiveDocument.TablesOfContents.Count = 0 Then
MsgBox "当前文档没有自动目录。", vbInformation
Exit Sub
End If
For Each toc In ActiveDocument.TablesOfContents
For Each f In toc.Range.Fields
If InStr(1, f.Code.Text, "PAGEREF", vbTextCompare) > 0 Then
startPos = f.Result.Start
endPos = FieldEndPos(f)
' 跳过已经处理过的(后面已经是"页"字的)
If ActiveDocument.Range(endPos, endPos + 1).Text <> "页" Then
starts.Add startPos
ends.Add endPos
End If
End If
Next f
Next toc
' 从后往前处理,避免前面插入字符导致后面位置错位
For i = starts.Count To 1 Step -1
endPos = CLng(ends(i))
startPos = CLng(starts(i))
If ActiveDocument.Range(endPos, endPos + 1).Text <> "页" Then
ActiveDocument.Range(endPos, endPos).Text = "页"
End If
ActiveDocument.Range(startPos, startPos).Text = "第"
Next i
MsgBox "已处理目录页码为""第X页""格式。", vbInformation
End Sub
Function FieldEndPos(ByVal f As Field) As Long
Dim p As Long
For p = f.Result.End To f.Result.End + 20
If p >= ActiveDocument.Range.End Then Exit For
If ActiveDocument.Range(p, p + 1).Text = ChrW(21) Then
FieldEndPos = p + 1
Exit Function
End If
Next p
FieldEndPos = f.Result.End
End Function
这样,
跑完之后,目录效果会从:
第1小节 概述..........................15
变成:
第1小节 概述..........................第15页
需要说明的word文档内容变更而导致页码改变时,需要重新运行宏
如果内容已经固定,可以打印来,可以使用ctrl+alt+f9来使TOC 域转成纯文本
另外,
{ TOC ... } -> ActiveDocument.TablesOfContents
{ INDEX ... } -> ActiveDocument.Indexes
图表目录 -> ActiveDocument.TablesOfFigures
书签 -> ActiveDocument.Bookmarks
跳转到书签的链接 -> ActiveDocument.Hyperlinks / Fields
+++
注册硅基流动的 API, 来使用大模型。
https://cloud.siliconflow.cn/i/gxlLJT5A
OR
🙋蹲队友拼智谱 Coding Plan!
🧩国内顶流编程大模型,20+主流工具全适配,性价比拉满,
👉立即参与「拼好模」:https://www.bigmodel.cn/glm-coding?ic=BQOSVRTBFC
OR
方舟 Coding Plan 最新支持 GLM-5.2、Kimi-K2.7 、MiniMax-M3、DeepSeek-V4 系列、Doubao-Seed-2.0 系列等模型,工具不限,现在订阅叠加9.5折,低至9.4元,订阅越多越划算!
立即订阅:https://volcengine.com/L/EqdSxoU56Bg/ 邀请码:KYNGTDZA
浙公网安备 33010602011771号