如何在VBA中确定所选内容正上方的Heading-X样式的标题?

时间:2019-04-19 19:57:38

标签: vba ms-word

我有一个带有多级标题的文档-目录,标题1-n的样式等等。当我拉起导航窗格并在文档内移动文本光标时,导航窗格会突出显示最靠近光标位置的标题。没有什么方法可以获取VBA中的标题-Range或Selection对象的某些属性吗?

在具有Word-Application对象WithEvents的类模块中,我编写了WindowSelectionChange事件处理程序以搜索样式为标题1或标题2的“ ^ p”,确定哪个更接近,获取该标题的文本,然后用它做东西。获取最接近的标题文本应该更简单,更快捷。

Private Sub appWord_WindowSelectionChange(ByVal Sel As Word.Selection)

    Dim lHdrPosn As Long, HP As Long
    Dim sStyle As String
    Dim rngSelPosn As Word.Range
    Dim sHdrText As String
    Dim lRTFposn As Long, lRTFselLength As Long

    With Sel

        If Not (.Document Is ThisDocument) Then Exit Sub

        Set rngSelPosn = .Range
        rngSelPosn.Collapse IIf(.StartIsActive, wdCollapseStart, wdCollapseEnd)

    End With

    With rngSelPosn

        lHdrPosn = -1

        For HP = 2 To 1 Step -1

            sStyle = "Heading " & HP
            With .Find                          ' Find a paragraph mark of style Heading (HP)

                .ClearFormatting
                .Style = sStyle
                .Forward = (Sel.Style = sStyle) ' This is case user clicks in a heading
                                                ' Get the later one
                If .Execute("^p") Then If lHdrPosn = -1 Or rngSelPosn.Start > lHdrPosn Then lHdrPosn = rngSelPosn.Start

            End With

        Next

        If lHdrPosn < 0 Then Exit Sub

    End With

    sHdrText = ThisDocument.Characters(lHdrPosn).Paragraphs(1).Range.Text
    With frmHelpWindow.rtfHelpText              ' Here's the header's text

        lRTFposn = .Find(vbCrLf & sHdrText & vbLf, 0, Len(.TextRTF))
        If lRTFposn < 0 Then Exit Sub

        lRTFselLength = .SelLength

        .SelStart = Len(.TextRTF)

        .SelStart = lRTFposn + 2
        .SelLength = lRTFselLength - 2

        .Refresh

    End With

End Sub

1 个答案:

答案 0 :(得分:0)

有一个旧的WordBasic书签可用于此目的。它需要Selection,所以光标位置很好:

Selection.Bookmarks("\HeadingLevel").Range

无论哪个级别,都要获取最接近的上一个标题段落:

Selection.Bookmarks("\HeadingLevel").Range.Paragraphs(1)

要获取标题文本(例如):

Selection.Bookmarks("\HeadingLevel").Range.Paragraphs(1).Range.Text