VBA单词,在页脚文本中添加页码

时间:2018-07-31 13:23:39

标签: 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", 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上也是错误的。如何在文本中添加正确的数字。我知道PageNumbers.Add存在,但这与我的文档页脚不太吻合。

2 个答案:

答案 0 :(得分:0)

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

目前尚不清楚应该如何看待您所做的工作。但是,假设页码位于其他信息的末尾:

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

答案 1 :(得分:0)

 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