user1415529
user1415529

Reputation: 41

Text of the preceding heading in word

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".

Upvotes: 4

Views: 3606

Answers (2)

Laurent CAPRANI
Laurent CAPRANI

Reputation: 139

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")

Upvotes: 3

Siddharth Rout
Siddharth Rout

Reputation: 149277

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

Upvotes: 2

Related Questions