vba - 使用 VBA 在 Word 文档的页脚中编辑页码
问题描述
我需要将页码从“1”更改为“—— 1 ——”(不是简短的——所以我不能简单地更改页码样式)。我怎样才能在 VBA 中做到这一点?
我尝试了以下代码,但第二个 —— 不知何故不在位。
Selection.HomeKey unit:=wdStory
Selection.GoTo wdGoToPage, wdGoToNext, , "15 "
If ActiveWindow.View.SplitSpecial <> wdPaneNone Then
ActiveWindow.Panes(2).Close
End If
If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow.ActivePane.View.Type = wdOutlineView Then
ActiveWindow.ActivePane.View.Type = wdPrintView
End If
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
If Selection.HeaderFooter.IsHeader = True Then
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageFooter
Else
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
End If
Selection.WholeStory
Selection.Font.Size = 14
Selection.Font.Name = "宋体"
Selection.InsertAfter " —"
Selection.InsertBefore "— "
ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
Selection.HomeKey unit:=wdStory
If ActiveWindow.View.SplitSpecial <> wdPaneNone Then
ActiveWindow.Panes(2).Close
End If
If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow.ActivePane.View.Type = wdOutlineView Then
ActiveWindow.ActivePane.View.Type = wdPrintView
End If
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
If Selection.HeaderFooter.IsHeader = True Then
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageFooter
Else
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
End If
Selection.WholeStory
Selection.Font.Size = 14
Selection.Font.Name = "宋体"
Selection.InsertAfter " —"
Selection.InsertBefore "— "
ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
End Sub
解决方案
看来问题中的代码是使用宏记录器生成的。SeekView
不是很可靠或效率不高。通常,最好直接使用 WordRange
对象,而不是Selection
. 这更快、更准确并减少了“屏幕闪烁”。
下面的代码示例使用该原则:它获取Range
当前页面的Footer
. 在页脚的整个内容之前和之后插入带有空格的长破折号字符。然后将格式应用于此内容。
请注意,对于 Word,如果应将此格式应用于整个文档的页脚,则更改页脚样式实际上会更好。
Sub InsertContentBeforeAndAfterPageNumber()
Dim rngFooter As Word.Range
Dim sCharToInsert As String
Selection.GoTo wdGoToPage, wdGoToNext, , "15"
sCharToInsert = "—"
Set rngFooter = Selection.Sections(1).Footers(wdHeaderFooterPrimary).Range
With rngFooter
.InsertBefore sCharToInsert & " "
.InsertAfter " " & sCharToInsert
.Font.Size = 14
.Font.Name = "宋体"
End With
End Sub
推荐阅读
- localization - Accept-Language 标头的典型中文语言代码是什么?
- windows - Pre/Post 修补脚本 - 运行脚本并从 VM 获取输出
- django - 我正在尝试在 Django 中的 auth_user 中创建用户,但我在 /register/set_password() 处收到此错误 TypeError missing 1 required
- jquery - AJAX 仅对某些用户失败
- linux - 哪个 Linux 内核版本支持 uffdio_writeprotect 结构以及如何编译和安装该 linux 内核?
- sql - 查找所有相关表中是否存在数据 (PL/SQL)
- coredns - 如果名称未解析,如何将请求转发给下一个解析器
- python - Home Assistant 无法从 Python/JSON MQTT 消息中提取数据
- c++ - 计算删除的迭代次数,直到数组被排序
- assembly - 在 Assembler 8086 中删除文件时出现问题