Text of the preceding heading in word

≯℡__Kan透↙ 提交于 2019-12-01 05:53:23

问题


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


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/10741389/text-of-the-preceding-heading-in-word

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!