Inserting text and fields in Word 2010 header without using .Select

只愿长相守 提交于 2019-12-04 04:52:36

问题


I am trying to fix up a Word 2010 page header containing fields for filename, save date and page number as well as some text between each, like so: filename+" "+save date+tab+page number. However, I can't seem to get the strings in their right places. What I have so far is this:

Sub CreateHeader()
    Dim myRange As Range
    With ActiveDocument
        Set myRange = .Sections(1).Headers(wdHeaderFooterPrimary).Range
        .Fields.Add Range:=myRange, Type:=wdFieldFileName, PreserveFormatting:=True
        myRange.Collapse wdCollapseEnd
        myRange.InsertAfter (" ")
        myRange.Collapse wdCollapseEnd
        .Fields.Add Range:=myRange, Type:=wdFieldSaveDate, Text:="\@ YYYY-MM-DD", PreserveFormatting:=True
        myRange.InsertAfter (Chr(9))
        myRange.Collapse wdCollapseEnd
        .Fields.Add Range:=myRange, Type:=wdFieldPage, PreserveFormatting:=True
    End With
End Sub

However, after executing the sub, the different parts are not were I intend. Instead, they show up as filename+" "+tab+page number+save date. What am I doing wrong here? If it is at all possible, I would prefer not resorting to .Select.

(Please note that I recently asked a similar question.)


回答1:


I believe your problem here stems from the fact that you set the myRange variable to the header text which, when empty, is simply the first (empty) character. After you add the Savedate it seems to go out of this original range. You need to add two things to make your code work.

Firstly, you want to collapse to the end after each insertion but you also need to redefine the header range (myRange variable) to the Header after inserting the SaveDate.

It's a bit ugly but the following code seems to do what you desire. Note that if I don't put the last wdCollapseEnd in the code it doesn't work.

Finally, I'd update your fields at the end just so you don't have to manually do it yourself.

Sub CreateHeader()
    Dim myRange As Range
    With ActiveDocument
        Set myRange = .Sections(1).Headers(wdHeaderFooterPrimary).Range
        .Fields.Add Range:=myRange, Type:=wdFieldFileName, PreserveFormatting:=True
        myRange.Collapse wdCollapseEnd
        myRange.InsertAfter (" ")
        myRange.Collapse wdCollapseEnd
        .Fields.Add Range:=myRange, Type:=wdFieldSaveDate, Text:="\@ YYYY-MM-DD", PreserveFormatting:=True
       Set myRange = .Sections(1).Headers(wdHeaderFooterPrimary).Range
       myRange.Collapse wdCollapseEnd
       myRange.InsertAfter (Chr(9))
       myRange.Collapse wdCollapseEnd
       .Fields.Add Range:=myRange, Type:=wdFieldPage, PreserveFormatting:=True
       myRange.Fields.Update
End With

End Sub



来源:https://stackoverflow.com/questions/14747261/inserting-text-and-fields-in-word-2010-header-without-using-select

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