Search code examples
vbams-word

Enter cyclic page numbers as footers in MS Word


I have a 200-page-long document. I want to mark the footers such that the first page reads 'Page 1 of 2', the second page reads 'Page 2 of 2', and again the third should read '1 of 2' and so on.

I am trying to use a VBA script as I don't want to use 'different first page' and then give section breaks every two pages.

Sub InsertCyclicFooters()
    Dim doc As Document
    Dim sec As Section
    Dim rng As Range
    Dim i As Integer
    Dim n As Integer
    
    Set doc = ActiveDocument
    n = 2
    
    For Each sec In doc.Sections
        Set rng = sec.Footers(wdHeaderFooterPrimary).Range
        
        i = rng.Information(wdActiveEndAdjustedPageNumber)
        
        i = (i - 1) Mod n + 1
        
        rng.Text = "Page " & i & " of " & n
        
        sec.Range.InsertBreak Type:=wdSectionBreakNextPage
    Next sec
    
    doc.Fields.Update
End Sub

This script marks each page as 'Page 1 of 2'.

I tried updating the fields with Ctrl + A followed by F9.


Solution

  • See if this is what you want:

    Sub InsertCyclicFooters()
        Dim doc As Document
        Dim sec As Section
        Dim rng As Range, rngGoto As Range
        Dim i As Integer
        Dim n As Integer
        Dim pageCount As Long, ur As UndoRecord
        
        Set ur = Word.Application.UndoRecord
        ur.StartCustomRecord "InsertCyclicFooters"
        
        Set doc = ActiveDocument
        n = 2
        
        pageCount = doc.Range.Information(wdNumberOfPagesInDocument)
        
        Set rng = doc.Characters(1)
        Do While i < pageCount
            i = rng.Information(wdActiveEndAdjustedPageNumber)
            Set rngGoto = rng.GoTo(wdGoToPage, wdGoToNext, 1)
    '        Do Until rngGoto.Information(wdActiveEndPageNumber) = i + 1
    '            rngGoto.Move Count:=-1
    '        Loop
            
            If i < pageCount Then
                rngGoto.InsertBreak Type:=wdSectionBreakNextPage
                Set rng = rng.Document.Sections(n).Range.Characters(1)
                n = n + 1
            End If
        Loop
        
        n = 2
        Set rngGoto = doc.Characters(1)
        For Each sec In doc.Sections
            
            sec.Footers(wdHeaderFooterPrimary).LinkToPrevious = False
            Set rng = sec.Footers(wdHeaderFooterPrimary).Range
            
            
            'i = rng.Information(wdActiveEndAdjustedPageNumber)
            i = rngGoto.Information(wdActiveEndAdjustedPageNumber)
            
            i = (i - 1) Mod n + 1
            
            rng.Text = "Page " & i & " of " & n
            
            'sec.Range.InsertBreak Type:=wdSectionBreakNextPage
            Set rngGoto = rng.GoTo(wdGoToPage, wdGoToNext, 1)
            
        Next sec
        
        doc.Fields.Update
        
        ur.EndCustomRecord
    End Sub