[英]How to determine in VBA the Heading-X styled heading just above the selection?
I have a document with multi-level headings -- table of contents, styles Heading 1-n, all that. 我有一个带有多级标题的文档-目录,标题1-n的样式等等。 When I pull up the Navigation Pane and move the text cursor within the document, the Navigation Pane highlights the heading closest to the cursor position.
当我拉起导航窗格并在文档内移动文本光标时,导航窗格会突出显示最靠近光标位置的标题。 Isn't there some way get what that heading is in VBA -- some property of the Range or Selection object?
没有某种方法可以获取VBA中的标题-Range或Selection对象的某些属性吗?
In a class module that has a Word-Application object WithEvents I've written a WindowSelectionChange event handler to search for "^p" with styled Heading 1 or Heading 2, determine which one is closer, get that heading's text and then do stuff with it. 在具有Word-Application对象WithEvents的类模块中,我编写了WindowSelectionChange事件处理程序,以搜索样式为“标题1”或“标题2”的“ ^ p”,确定哪个更接近,获取该标题的文本,然后执行以下操作它。 It should be simpler and faster to get the nearest heading's text.
获取最接近的标题文本应该更简单,更快捷。
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
There's an old WordBasic bookmark that can be used for this. 有一个旧的WordBasic书签可用于此目的。 It requires
Selection
, so the cursor position is fine: 它需要
Selection
,所以光标位置很好:
Selection.Bookmarks("\HeadingLevel").Range
To get the closest, previous heading paragraph, no matter which level: 要获得最接近的前一个标题段落,无论级别如何:
Selection.Bookmarks("\HeadingLevel").Range.Paragraphs(1)
To get the text of the heading (for example): 要获取标题文本(例如):
Selection.Bookmarks("\HeadingLevel").Range.Paragraphs(1).Range.Text
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.