Vba 页脚第X页,共Y页

Vba 页脚第X页,共Y页,vba,ms-word,Vba,Ms Word,我有以下vba代码 Sub pageNumber(objOutputDoc As Object) ' With objOutputDoc.Sections(objOutputDoc.Sections.Count) ' .Footers(wdHeaderFooterPrimary).Range.Text = vbTab & vbTab & "Page " ' .Footers(wdHeaderFooterPrimary

我有以下vba代码

    Sub pageNumber(objOutputDoc As Object)

'    With objOutputDoc.Sections(objOutputDoc.Sections.Count)
'        .Footers(wdHeaderFooterPrimary).Range.Text = vbTab & vbTab & "Page "
'        .Footers(wdHeaderFooterPrimary).PageNumbers.Add FirstPage:=True
'    End With
    Dim i As Long, bAdd As Boolean: bAdd = True
    With objOutputDoc.Sections(objOutputDoc.Sections.Count).Footers(wdHeaderFooterPrimary).Range 'First.Headers(wdHeaderFooterPrimary).Range
      For i = 1 To .Fields.Count
        If .Fields(i).Type = wdFieldPage Then
          bAdd = False: Exit For
        End If
      Next
      If bAdd = True Then
        .InsertAfter vbTab & vbTab & "Page "
        .Fields.Add .Characters.Last, wdFieldEmpty, "PAGE", False
        .InsertAfter " of "
        .Fields.Add .Characters.Last, wdFieldEmpty, "NUMPAGES", False
      End If
    End With
End Sub

上述vba代码会自动将第X页(共Y页)添加到我的word文档中。例如,我的word文档包含27页,因此当我运行vba时,页码将插入第1页(共27页)、第2页(共27页)等。我的最后一页(即第27页)出现问题,我已在最后一页(共1页)的底部插入。当我运行vba时,第27页(共27页)插入最后一页,现在我有第1页(共1页)和第27页(共27页)。我希望倒数第二页是第26页,共26页。

如果第1页到第26页在同一节中,您可以通过使用
SECTIONPAGES
而不是
NUMPAGES
来实现您的目标

然后,对于以下部分,您需要重新启动页面编号:

With objOutputDoc.Sections(objOutputDoc.Sections.Count).HeaderFooter.PageNumbers
    .RestartNumberingAtSection = True
    .StartingNumber = 1
End With