0
votes

I am trying to make a macro for word. I have many word docs with 2 pages or more and they have same headers, footers I am trying to make a macro which will add an additional blank page to the doc but should not carry any header/footer and should not affect the previous pages. So a new blank page with basically nothing.

    Selection.EndKey Unit:=wdStory
    Selection.InsertBreak Type:=wdSectionBreakNextPage
    Selection.InsertNewPage

    Selection.Sections(1).Headers(wdHeaderFooterPrimary).LinkToPrevious = False
    Selection.Sections(1).Headers(wdHeaderFooterPrimary).Range.Delete
    Selection.Sections(1).Footers(wdHeaderFooterPrimary).LinkToPrevious = False
    Selection.Sections(1).Footers(wdHeaderFooterPrimary).Range.Delete

So far this macro gives me an additional page with header/footer followed by a blank page. Any thoughts/ideas?

1

1 Answers

1
votes

The code in the question is on the right track with using the Section object, LinkToPrevious and Range.Delete. What's generating the additional page is

Selection.InsertNewPage

The line Selection.InsertBreak Type:=wdSectionBreakNextPage already creates a new page.

FWIW, the code I'd use would be the same in principle, but would work with Range instead of the Selection object. Working with a Range is generally faster and there's minimal screen flicker. It also tends to be more accurate, and it's easier to determine what the code is affecting. I'm providing it for information purposes :-)

Sub NewPageSectionNoHF()
    Dim doc As Word.Document
    Dim rng As Word.Range
    Dim sec As Word.Section
    Dim hf As Word.HeaderFooter

    Set doc = ActiveDocument
    Set rng = doc.content
    rng.Collapse wdCollapseEnd
    rng.InsertBreak Word.WdBreakType.wdSectionBreakNextPage
    Set sec = rng.Sections(1)

    'First page
    Set hf = sec.Headers(wdHeaderFooterFirstPage)
    If hf.exists Then
        hf.LinkToPrevious = False
        hf.Range.Delete
    End If
    Set hf = sec.Footers(wdHeaderFooterFirstPage)
    If hf.exists Then
        hf.LinkToPrevious = False
        hf.Range.Delete
    End If

    'Other pages
    Set hf = sec.Headers(wdHeaderFooterPrimary)
    hf.LinkToPrevious = False
    hf.Range.Delete
    Set hf = sec.Footers(wdHeaderFooterPrimary)
    hf.LinkToPrevious = False
    hf.Range.Delete
End Sub