Reputation: 41
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
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
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
Upvotes: 2