VBA word,将页码添加到页脚文本

VBA word,将页码添加到页脚文本,vba,ms-word,Vba,Ms Word,我有一个页脚文本,需要用VBA宏替换,这就是我正在做的: 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

我有一个页脚文本,需要用VBA宏替换,这就是我正在做的:

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
除一条线路外,其他线路均适用:

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

页码始终为3,这在第一个编号的第2页上也是错误的。如何在文本中添加正确的数字。我知道PageNumber.Add存在,但这与我的文档页脚不一致。

您不应该尝试使用页脚(或页眉)中的静态文本对Word中的页面进行编号。页脚中显示的内容会在每页上重复-这就是页脚的工作方式。使用页面字段代码,该代码将根据实际页面动态更新

现在还不完全清楚你所做的事情的结果应该是怎样的。但假设页码位于其他信息的末尾:

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

你的问题有答案吗?@Cindymister找到了自己的解决办法
 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