Insert two fields in Word 2010 page header using VBA

孤者浪人 提交于 2019-12-11 02:47:28

问题


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

回答1:


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:

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:

myRange.Collapse wdCollapseEnd
ActiveDocument.Fields.Add Range:=myRange, Type:=wdFieldEmpty, Text:="FileName", PreserveFormatting:=True


来源:https://stackoverflow.com/questions/14710750/insert-two-fields-in-word-2010-page-header-using-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!