2
votes

I have a footer-text that I need to replace with VBA macros and this is what I am doing:

With ActiveDocument.Sections(1).Footers(wdHeaderFooterPrimary)
        text = Replace(.Range.text, "SITECODE", ws.Cells(24, 2))
        text = Replace(text, "STREET", ws.Cells(6, 2))
        text = Replace(text, "SITENAME", ws.Cells(18, 2))
        text = Replace(text, "POSTALCODE", ws.Cells(2, 2))
        text = Replace(text, "Page number:", "Page number: " & wdActiveEndPageNumber)
        .Range.text = Replace(text, "CITY", ws.Cells(10, 2))

    End With

This works except for one line:

 text = Replace(text, "Page number:", "Page number: " & wdActiveEndPageNumber)

The pagenumber is always 3, which is also wrong on the first numbered page 2. How can I add the right number to text. I know that PageNumbers.Add exists but this does not align well with my document footer.

2
Has your question been answered?Cindy Meister
@CindyMeister found own solutionfangio

2 Answers

1
votes

You shouldn't try to number pages in Word using static text in a footer (or header). What's displayed in a footer repeats on EVERY PAGE - that's how footers work. Use a PAGE field code, which will dynamically update according to the actual page.

It's not completely clear how the result of what you're doing is supposed to look. But on the assumption the page number would be at the end of the other pieces of information:

Dim doc As Word.Document
Dim rng As Word.Range

Set doc = ActiveDocument
Set rng = doc.Sections(1).Footers(wdHeaderFooterPrimary).Range
rng.Text = "Sitecode" & vbCr & "Sitename" & "Street" & vbCr & _
           "City PostalCode " & vbCr & "Page number: "
rng.Collapse wdCollapseEnd
rng.Fields.Add rng, , "Page ", False
0
votes
 For Each wd In .Range.Words
            If StrComp(wd, "PNR", vbTextCompare) = 0 Then
                Selection.Fields.Add Range:=wd, Type:=wdFieldEmpty, text:="PAGE  \* Arabic ", PreserveFormatting:=True
            End If
        Next wd