View Single Post
 
Old 02-11-2023, 06:28 AM
Ddadoo57 Ddadoo57 is offline Windows 11 Office 2021
Advanced Beginner
 
Join Date: Feb 2023
Posts: 90
Ddadoo57 is on a distinguished road
Default

Quote:
Originally Posted by gmayor View Post
The error occurs if there are fields in the footer and the field codes are not visible. Fix it with
Code:
Sub Macro1()
Dim oSection As Section
Dim oFooter As HeaderFooter
Dim oRng As Range
Dim bCodes As Boolean
    bCodes = ActiveWindow.ActivePane.View.ShowFieldCodes
    ActiveWindow.ActivePane.View.ShowFieldCodes = True
    For Each oSection In ActiveDocument.Sections
        For Each oFooter In oSection.Footers
            If oFooter.Exists Then
                Set oRng = oFooter.Range
                With oRng
                    .Collapse 0
                    .Fields.Add Range:=oRng, Type:=wdFieldIf, Text:="{PAGE} = {NUMPAGES} ""last page""", PreserveFormatting:=False
                    .Collapse 1
                    .MoveEndUntil "}"
                    .End = .End + 1
                    .MoveStartUntil "{"
                    oRng.Select
                    .Text = ""
                    .Fields.Add Range:=oRng, Type:=wdFieldPage, PreserveFormatting:=False
                    .Collapse 0
                    .MoveEndUntil "}"
                    .End = .End + 1
                    .MoveStartUntil "{"
                    .Text = ""
                    .Fields.Add Range:=oRng, Type:=wdFieldNumPages, PreserveFormatting:=False
                    .Fields.Update
                End With
            End If
        Next oFooter
    Next oSection
    ActiveWindow.ActivePane.View.ShowFieldCodes = bCodes
lbl_Exit:
    Set oSection = Nothing
    Set oFooter = Nothing
    Set oRng = Nothing
    Exit Sub
End Sub


Thank you Gmayor,

I will adapt the code to my needs and send you back what I have modified and/or added. Maybe it will help someone a little bit too.

If not, I only had hidden fields in the headers, not in the footers. It's amazing that it takes that into account.

Best regards,
Reply With Quote