The text of the previous heading in the word

Given any word or paragraph selected in Word, is there a way to use VBA to find the text of the nearest previous heading?

For instance:

Title Level 1: Basic Title This is a paragraph about a document. (A) Heading level 2: subtitle This paragraph describes the part. (B)

If any part (B) is selected, I want to find "A Sub Title". If any part (A) is selected, I want to find "Main Name".

+3
source share
2 answers

Is that what you are trying?

Option Explicit

Sub Sample()
    Do
        Selection.MoveUp Unit:=wdLine, Count:=1

        Selection.HomeKey Unit:=wdLine
        Selection.EndKey Unit:=wdLine, Extend:=wdExtend

        If ActiveDocument.ActiveWindow.Selection.Information(wdFirstCharacterLineNumber) = 1 Then Exit Do
    Loop Until Selection.Style <> "Normal"

    MsgBox Selection.Style
End Sub

Sanpshot

enter image description here

+2
source

There is a special in the previous header WdGoToItem:

Dim heading As Range
Set heading = selection.GoTo(What:=wdGoToHeading, Which:=wdGoToPrevious)

' Display heading text
heading.Expand Unit:=wdParagraph
MsgBox heading.Text

Here's a little trick to get the entire current heading level from anywhere in the document:

Dim headingLevel as Range
' headingLevel encompasses the region under the preceding heading
Set headingLevel = Selection.GoTo(What:=wdGoToBookmark, Name:="\HeadingLevel")
+2

All Articles