user918967
user918967

Reputation: 2167

MS Word VBA to link previous footer for multiple sections and pages

I have a MS Word (2010) and my document has hundreds of sections when I really only need a limited number of sections with the same footer.

I'd like a macro that can cycle through the selected pages and change all the footers to Link to Previous.

I recorded a macro which will do it for one section, how do I alter the code so if I selected a bunch of pages (e.g. 25) it will zip through all of them?

Sub LinkToPrev_Foot()
'
' LinkToPrev_Foot Macro
'
'
    Selection.HeaderFooter.LinkToPrevious = Not Selection.HeaderFooter. _
        LinkToPrevious
   ' ActiveWindow.ActivePane.View.NextHeaderFooter
End Sub

Upvotes: 1

Views: 1128

Answers (2)

Nor.Z
Nor.Z

Reputation: 1349

another raised issue

the other answer already gave a good solution.

However, it doesnt quite work in my case -- some of the Section.Footers fail to LinkToPrevious = True.

I dont know why.

solution (workaround)

Then I tried to reset the Footer for each Section to see if it can solve the issue. And it did.

Sub aa_test_main()
  ' >>
  Dim sec As Section
  For Each sec In Selection.Sections ' ActiveDocument.Sections
    ' ( `If sec.Index > 1` is not needed, cuz: 
    ' ( its only for the First page in the document, 
    ' ( when you are using Selection, its unlikely you would select the First page (slight performance boost)
    With sec.Footers(wdHeaderFooterPrimary)
      ' @key:
      ' You must delete the Footer, then add it back (for resetting it). 
      ' Otherwise, the `LinkToPrevious = True` may not work for some Sections.
      ' (idk why)
      ' @atten: This will delete the format of your Footer!!! & only add back a PageNum. 
      .Range.Delete 
      .PageNumbers.Add
      .LinkToPrevious = True ' @main
    End With
    ' Debug.Print "--- " & sec.Index & sec.Footers(wdHeaderFooterPrimary).LinkToPrevious
  Next
End Sub
  • Attention: .Range.Delete This will delete the format of your Footer!!! & .PageNumbers.Add only add back a PageNum.

    You may NOT want this behavior.

  • (this is only a workaround, waiting for a better solution.)

Upvotes: 0

Timothy Rylatt
Timothy Rylatt

Reputation: 7850

You need to loop through the sections of the document. The code below assumes you are only using one of the three types of footer.

Public Sub LinkToPrev_Foot()
    Dim ftr As HeaderFooter
    Dim sec As Section

    For Each sec In ActiveDocument.Sections
        'can't link the first section to a previous one
        If sec.Index > 1 Then
            'if document has other types of footer you'll need to loop through them
            sec.Footers(wdHeaderFooterPrimary).LinkToPrevious = True
        End If
    Next sec
End Sub

Upvotes: 2

Related Questions