使用 VBA 在 Word 2010 页眉中插入两个字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14710750/
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
Insert two fields in Word 2010 page header using VBA
提问by Fredrik P
I am trying to insert two fields in a page header. I am able to insert them at the current selection (see code below), but I would prefer not having to select the page header before inserting the fields. Can this be done?
我正在尝试在页眉中插入两个字段。我可以在当前选择中插入它们(请参阅下面的代码),但我希望在插入字段之前不必选择页眉。这能做到吗?
Sub insertFields()
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:="DOCPROPERTY LastSavedTime ", PreserveFormatting:=True
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:="FileName", PreserveFormatting:=True
End Sub
采纳答案by joeschwa
If you specify the section of the document to place the field in as well as the type of header (wdHeaderFooterPrimary
, wdHeaderFooterFirstPage
or wdHeaderFooterEvenPages
) you can use this code:
如果您指定要放置字段的文档部分以及标题类型(wdHeaderFooterPrimary
,wdHeaderFooterFirstPage
或wdHeaderFooterEvenPages
),您可以使用以下代码:
Dim myRange As Range
Set myRange = ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Range
ActiveDocument.Fields.Add Range:=myRange, Type:=wdFieldEmpty, Text:="DOCPROPERTY LastSavedTime ", PreserveFormatting:=True
Additional Information in response to comment
回复评论的附加信息
You can use the Collapse
method, which places the insertion point at the start or end position of a range, to insert multiple fields within the header. Add appropriate additional code to insert spaces, formatting or carriage returns:
您可以使用将Collapse
插入点置于范围的开始或结束位置的方法在标题中插入多个字段。添加适当的附加代码以插入空格、格式或回车:
myRange.Collapse wdCollapseEnd
ActiveDocument.Fields.Add Range:=myRange, Type:=wdFieldEmpty, Text:="FileName", PreserveFormatting:=True