如何在VBA中确定选择上方的标题-X样式标题?

问题描述 投票:1回答:1

我有一个包含多级标题的文档 - 目录,样式标题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
vba ms-word
1个回答
0
投票

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

Selection.Bookmarks("\HeadingLevel").Range

要获得最接近的前一个标题段落,无论哪个级别:

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

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

Selection.Bookmarks("\HeadingLevel").Range.Paragraphs(1).Range.Text
热门问题
推荐问题
最新问题