0
votes

I'm building my footers via code. I'm having an issue properly formatting the page counts in my Word footer when adding the fields via VBA. When the code runs the formatting always ends up as XXof XX (1of 20) instead of XX of XX (1 of 20). I have tried the following but the numbers always show the page number without a space before the word "of".

    With rng
        .Text = "NUMPAGES "
        Set oFooterRng1 = rng.Words(1)
        .Fields.Add Range:=oFooterRng1, Type:=wdFieldEmpty, Text:="NUMPAGES  \* Arabic ", PreserveFormatting:=True
    End With
    rng.Collapse wdCollapseStart
    rng.Text = " of "
    rng.Collapse wdCollapseStart
    With rng
        .Text = "PAGE "
        Set oFooterRng1 = rng.Words(1)
        .Fields.Add Range:=oFooterRng1, Type:=wdFieldEmpty, Text:="PAGE  \* Arabic ", PreserveFormatting:=True
    End With

or this

    With rng
        .Text = "PAGE of NUMPAGES "
        Set oFooterRng1 = rng.Words(1)
        Set oFooterRng2 = rng.Words(3)
        .Fields.Add Range:=oFooterRng1, Type:=wdFieldEmpty, Text:="PAGE  \* Arabic ", PreserveFormatting:=True
        .Fields.Add Range:=oFooterRng2, Type:=wdFieldEmpty, Text:="NUMPAGES  \* Arabic ", PreserveFormatting:=True
    End With
1
Might be worth trying adding the space character in to the string? e.g. rng.Text = Chr(32) & "of "Samuel Everson
Thanks for the suggestion, but that didn't work.FlyFish

1 Answers

2
votes

Try something based on:

Sub Demo()
Application.ScreenUpdating = False
With ActiveDocument.Sections(1).Footers(wdHeaderFooterPrimary).Range
  .InsertAfter Text:="Page "
  .Fields.Add Range:=.Characters.Last, Type:=wdFieldEmpty, Text:="PAGE", PreserveFormatting:=False
  .InsertAfter Text:=" of "
  .Fields.Add Range:=.Characters.Last, Type:=wdFieldEmpty, Text:="NUMPAGES", PreserveFormatting:=False
End With
Application.ScreenUpdating = True
End Sub

And, to do it in reverse as you're trying to achieve:

Sub Demo()
Application.ScreenUpdating = False
With ActiveDocument.Sections(1).Footers(wdHeaderFooterPrimary).Range
  .Fields.Add Range:=.Characters.Last, Type:=wdFieldEmpty, Text:="NUMPAGES", PreserveFormatting:=False
  .Collapse wdCollapseStart
  .Text = " of "
  .Collapse wdCollapseStart
  .Fields.Add Range:=.Duplicate, Type:=wdFieldEmpty, Text:="PAGE", PreserveFormatting:=False
  .Collapse wdCollapseStart
  .Text = "Page "
End With
Application.ScreenUpdating = True
End Sub