Question

I am trying to delete sections contained within a heading from a Word document using VBA code. A section, in my situation, refers to a listing in the Navigation Pane on the left side of the screen.

For example, I would search for a top level heading of "Introduction", and delete it, then the next top level heading would be "Body" with three subsections below it. I would select the "Body" section and delete it. It's all very easy to do within Word itself, but I would like to do it through VBA. I have tried recording a macro while deleting from the Navigation Pane, but it doesn't record anything.

Edit: alternately, being able to use VBA to highlight the heading, and everything below it and up to a heading of equal or greater size, would also work.

Any ideas or suggestions are greatly appreciated, thanks!

Was it helpful?

Solution

The "Record macro" feature does not record anything, because you are able to select the section only using the mouse. It is known that "Recording Macro" tool does not work well with mouse. I've tried different things in my Word to solve the problem. I think, the most trivial and simple way, as you already noted in your edit, is to delete all the text below, till another heading or end-of-text is reached:

Selection.Find.ClearFormatting
With Selection.Find
    .Text = "Introduction"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchKashida = False
    .MatchDiacritics = False
    .MatchAlefHamza = False
    .MatchControl = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With
Selection.Find.Execute
unitsDeleted = Selection.Delete(wdCharacter, 2)
While (Selection.Style <> ActiveDocument.Styles("Heading 1")) And (unitsDeleted <> 0)
     unitsDeleted = Selection.Delete
Wend

In other words, are searching "Introduction" string in your document. Then you delete all the characters till the style of current character is "Heading 1" (or, another style, that you specify). You may also search for "Introduction" word with specific style, say "Heading 1". Record a macro, and check out, how it is performed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top