问题
I am tying to stamp a document variable field in the footer of every page in a document. I have figured out how to add the field. However, in doing so, the page numbering field that already exists in the footer becomes disabled, leaving only the text and no longer acting as a dynamic page number. Any help would be appreciated.
Here is my code that adds the field, but disables the page numbers somehow. (the "sectionFooter.Range.Text = sectionFooter.Range.Text + " "" line is the only way I could find to even get the page number to still show):
For Each docSection In ActiveDocument.Sections
For Each sectionFooter In docSection.Footers
sectionFooter.Range.Collapse wdCollapseEnd
sectionFooter.Range.Text = sectionFooter.Range.Text + " "
sectionFooter.Range.Collapse wdCollapseEnd
Dim newPP As Paragraph
Set newPP = sectionFooter.Range.Paragraphs.Add()
newPP.Range.Font.Size = 8
newPP.Range.Font.Name = "Arial"
ActiveDocument.Fields.Add Range:=newPP.Range, Type:=wdFieldEmpty, Text:="DOCVARIABLE ndGeneratedStamp", preserveformatting:=False
Next
Next
回答1:
If that is how you want the new field positioned, then try something like this ...
Dim docSection As word.Section, sectionFooter As word.HeaderFooter
Dim rng As word.Range
For Each docSection In ActiveDocument.Sections
For Each sectionFooter In docSection.Footers
Set rng = sectionFooter.Range
rng.InsertParagraphAfter
rng.Collapse wdCollapseEnd
rng.Font.Size = 8
rng.Font.Name = "Arial"
rng.Fields.Add Range:=rng, Type:=wdFieldEmpty, Text:="DOCVARIABLE ndGeneratedStamp", PreserveFormatting:=False
Next
Next
回答2:
Rich's answer handled the heavy lifting, but for anyone who happens upon this, wanted to spell out how I was also able to isolate the new paragraph and apply the font.
Set rng = sectionFooter.Range
rng.InsertParagraphAfter
Set rng = sectionFooter.Range
rng.Collapse wdCollapseEnd
Set newPP = rng.Paragraphs.Last
newPP.Range.Font.Size = 8
newPP.Range.Font.Name = "Arial"
rng.Fields.Add Range:=newPP.Range, Type:=wdFieldEmpty, Text:="DOCVARIABLE ndGeneratedStamp", preserveformatting:=False
回答3:
Based on my test, we can just remove the commented code too.
Note If we use this way, we need to set the page-number first then run the Macro.
Dim docSection As Word.Section, sectionFooter As Word.HeaderFooter
For Each docSection In ActiveDocument.Sections
For Each sectionFooter In docSection.Footers
'sectionFooter.Range.Collapse wdCollapseEnd
'sectionFooter.Range.Text = sectionFooter.Range.Text + " "
sectionFooter.Range.Collapse wdCollapseEnd
Dim newPP As Paragraph
Set newPP = sectionFooter.Range.Paragraphs.Add()
newPP.Range.Font.Size = 8
newPP.Range.Font.Name = "Arial"
ActiveDocument.Fields.Add Range:=newPP.Range, Type:=wdFieldEmpty, Text:="DOCVARIABLE ndGeneratedStamp", preserveformatting:=False
Next
Next
来源:https://stackoverflow.com/questions/51866047/ms-word-vba-adding-document-property-field-to-footer-removes-existing-page-n