Home > Mobile >  Insert page number with adding some number of pages
Insert page number with adding some number of pages

Time:12-18

I need to insert into a document's footer a page number in this form:

{ ={ PAGE }   n}

where n is getting from the UserForm's text field. I've tried this:

dim r as Range
set r = doc.Sections(1).Footers(wdHeaderFooterPrimary).Range.Fields(1).Code
doc.Sections(1).Footers(wdHeaderFooterPrimary).Range.Fields(1).Delete
n = UserForm1.TXT.text
r.Fields.Add Range:=r, Type:=wdFieldEmpty, Text:=" ={ PAGE }   "   n
doc.Sections(1).Footers(wdHeaderFooterPrimary).Range.Fields.Update

This macro inserts the text properly, but it gives a syntax error in the footer (it doesn't like the "{" bracket). How can I insert this field?

CodePudding user response:

I see that your code deletes the first field in the primary footer. Assuming, therefore, there is always a field there coded as per your { ={ PAGE } n}, all you need is:

Sub UpdatePageField()
With ActiveDocument
  .ActiveWindow.View.ShowFieldCodes = True
  With .Sections(1).Footers(wdHeaderFooterPrimary).Range
    .Find.Execute FindText:="=^19 PAGE ^21   " '{ ={ PAGE }   n}
    If .Find.Found = True Then
      .Collapse wdCollapseEnd
      .MoveEnd wdWord, 1
      .Text = UserForm1.TXT.Text
    End If
  End With
  .ActiveWindow.View.ShowFieldCodes = False
End With
End Sub
  • Related