使用 VBA 在 Word 中添加页码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24515203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add page number in Word using VBA
提问by Laurent Crivello
I am looking for hours for one of the simplest things to do (but with MS things are never simple...): How can I programmatically add in my Word footer 'Page #', using VBA ?
There are zillions of different ways on the internet but none is working. Just a couple of examples
我正在为最简单的事情之一寻找几个小时(但对于 MS,事情从来都不是简单的......):如何使用 VBA 以编程方式添加 Word 页脚“Page #”?
互联网上有无数种不同的方式,但都没有奏效。举几个例子
This code fails at Fields.Add:
此代码在 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
This code doesn't allow me to add a word like 'page' before:
这段代码不允许我在之前添加像“page”这样的词:
With ActiveDocument.Sections(1)
.Footers(wdHeaderFooterPrimary).PageNumbers.Add _
PageNumberAlignment:=wdAlignPageNumberLeft, _
FirstPage:=True
End With
Any additional hint ?
Thanks.
任何额外的提示?
谢谢。
回答by Laurent Crivello
OK, the following code finally works:
好的,下面的代码终于起作用了:
With objWord.ActiveDocument.Sections(Section)
.Footers(wdHeaderFooterPrimary).Range.Text = vbTab & "Page "
.Footers(wdHeaderFooterPrimary).PageNumbers.Add FirstPage:=True
End With
回答by d_or2000
This works for me. It will add "Page ## of ##" at the center of the footer:
这对我有用。它将在页脚的中心添加“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