首页 > 解决方案 > 使用 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

在此处输入图像描述

在此处输入图像描述

标签: vbams-wordpage-numbering

解决方案


看来问题中的代码是使用宏记录器生成的。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

推荐阅读