4
votes

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

For example:

Heading Level 1: The Main Title This is a paragraph about the document. (A) Heading Level 2: A Sub Title This paragraph describes a detail.(B)

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

2

2 Answers

3
votes

There is a special WdGoToItem towards the previous heading:

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

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

Here is a little known trick to get the whole current heading level from anywhere within a document:

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

Is this 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