0
votes

I would like to delete all headings (i.e. styles "Heading 1" and "Heading 2") that don't have body text below it. To clarify, this is what I mean.

  • Before running macro:

Fruits

Apples and Bananas

Vegetables

Grain

Bread and Pasta

  • AFTER running macro:

Fruits

Apples and Bananas

Grain

Bread and Pasta

1

1 Answers

0
votes

This can be done using a simple iteration over the paragraphs contained in the document:

Sub CleanupHeadings()

    Dim p As Paragraph
    Dim pNext As Paragraph

    For Each p In ActiveDocument.Paragraphs
        If IsHeading(p) Then
            ' check the following paragraph
            Set pNext = p.Next
            If Not pNext Is Nothing Then
                If IsHeading(pNext) Then
                    ' next paragraph is a heading too, so delete current paragraph
                    p.Range.Delete
                End If
            Else
                ' no following paragraph, i.e. document ends with a heading
                p.Range.Delete
            End If
        End If
    Next

End Sub

Function IsHeading(para As Paragraph) As Boolean

    IsHeading = para.OutlineLevel < wdOutlineLevelBodyText

End Function