0
votes

I aim to remove sections based on user input from an Excel document but I do not see a way of selecting a specific section within the Word document and removing it.

By sections I mean heading sections e.g. heading 12.4 has text and I would like the entire section (12.4) to be removed.

The code that is used when a section is deleted in Word:

Selection.Delete Unit:=wdCharacter, Count:=1

How do I make this specific to a section within the document?

Is there a way of defining the sections within the document in VBA and then calling upon them within a line of code similar to the above?

2

2 Answers

3
votes

Deleting all content associated with a particular heading is as simple as:

Sub DeleteHeadingRange()
Selection.Range.GoTo(What:=wdGoToBookmark, Name:="\HeadingLevel").Text = vbNullString
End Sub

Be warned: The text associated with a particular heading spans all the content from the current or preceding heading to the next one of the same or higher level (i.e. Heading 1 is higher than Heading 2).

0
votes

You need to be careful of your terminology because the term Section has a very specific meaning in Word, a meaning which is not related to Headings.

I'm assuming that your users have correctly used Headings rather than just adding a number to a line of text. In which case the following sub will remove a section of text between two paragraphs of the same outline level (Including the starting text).

Option Explicit

Public Sub ttest()
    RemoveSectionUsingParagraphLevel Selection.Range
End Sub

Public Sub RemoveSectionUsingParagraphLevel(ByVal ipRange As Word.Range)

    ' Heading level 1 = outline level 1
    ' Heading level 9 = outline level 9
    ' normal text = outline level 10

    Dim myLevel As Long
    myLevel = ipRange.Paragraphs.Item(1).OutlineLevel

    Dim myStart As Long
    myStart = ipRange.Start

    ipRange.Collapse direction:=wdCollapseEnd

    Do

        ipRange.MoveStart unit:=wdParagraph

    Loop Until ipRange.Paragraphs.Item(1).OutlineLevel = myLevel

    ipRange.Document.Range(Start:=myStart, End:=ipRange.Start - 1).Delete

End Sub