【问题标题】:Add page number in Word using VBA使用 VBA 在 Word 中添加页码
【发布时间】:2014-07-01 16:29:26
【问题描述】:

我正在寻找最简单的事情之一(但对于 MS,事情从来都不是简单的......):如何使用 VBA 以编程方式在我的 Word 页脚“页码”中添加?
那里互联网上有无数种不同的方式,但没有一种是有效的。举几个例子

此代码在 Fields.Add 失败:

Sub pageNumber()
    ActiveDocument.Sections(ActiveDocument.Sections.Count) _
        .Headers(wdHeaderFooterPrimary).Range.Select
    With Selection
        .Paragraphs(1).Alignment = wdAlignParagraphCenter
        .TypeText Text:="Page "
        .Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
            "PAGE ", PreserveFormatting:=True
        .TypeText Text:=" of "
        .Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
            "NUMPAGES ", PreserveFormatting:=True
    End With
End Sub

这段代码不允许我在前面添加“page”之类的词:

With ActiveDocument.Sections(1) 
 .Footers(wdHeaderFooterPrimary).PageNumbers.Add _ 
 PageNumberAlignment:=wdAlignPageNumberLeft, _ 
 FirstPage:=True 
End With

还有其他提示吗?
谢谢。

【问题讨论】:

  • 您能否通过在您的问题中添加您尝试过但不起作用的特定方式的代码来扩展“互联网上无数种不同的方式,但没有一种方式有效”?也许我们可以帮助您解决问题。
  • 你为什么不问 Word。您所要做的就是记录这些步骤。工具菜单 - 宏 - 录制新宏(Alt T、M、R 或单击状态栏)。这是 VBA 程序员的基本技能。
  • 谢谢,但是录制宏也没有帮助。由于复制发生在 Excel 和 Word 中的粘贴,出于某种原因,这给了我问题。在 Excel 中手动复制并在 Word 中以编程方式粘贴失败,而相反的工作正常。我已经用一些经过测试(但失败)的代码更新了这个问题。
  • 请忽略我上面的评论,因为我对另一个问题感到困惑。然而,录制宏并不能令人信服,因为它需要使用特定的模板,并且简单地复制/粘贴代码也不起作用。

标签: vba ms-word page-numbering


【解决方案1】:

好的,下面的代码终于可以运行了:

With objWord.ActiveDocument.Sections(Section)
    .Footers(wdHeaderFooterPrimary).Range.Text = vbTab & "Page "
    .Footers(wdHeaderFooterPrimary).PageNumbers.Add FirstPage:=True
End With

【讨论】:

  • 我在清理word文档的excel VBA宏中使用了类似的东西。对于这种情况,我发现了两点:第一,需要添加词对象库,见support.office.com/en-us/article/…。其次,像Set WordDoc = WordApp.Documents.Open(File) 这样的东西,然后With WordDoc.Sections(1) .Headers(wdHeaderFooterPrimary).PageNumbers.Add FirstPage:=False End With 有效——与这个答案非常相似。
【解决方案2】:

这对我有用。它将在页脚的中心添加“Page ## of ##”:

Sub Insert_PageNumber()

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 = wdSeekCurrentPageFooter
Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter

Selection.TypeText Text:="Page "

Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
    "PAGE  \* Arabic ", PreserveFormatting:=True

Selection.TypeText Text:=" of "

Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
    "NUMPAGES  ", PreserveFormatting:=True

ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument

End Sub

【讨论】:

    猜你喜欢
    • 2019-01-07
    • 2020-12-24
    • 2016-11-23
    • 1970-01-01
    • 1970-01-01
    • 2018-08-17
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    相关资源
    最近更新 更多