上下文:通过VBA或VSTO进行Microsoft Word编程。
Word文档对象的Comments属性允许枚举Word文档中的所有注释。
如何找到Word评论的当前标题?
示例文件:
标题1
标题1.1
(意见A)
输出: 评论A - 标题1.1
答案 0 :(得分:1)
我找不到更简单的方法,但它正在发挥作用。以下代码在活动文档中的第一个注释之前搜索最后一个标题。您可以使用For Each loop
轻松地将其用于所有评论。
Sub Heading_Above_Comment()
Dim COMM As Comment
Set COMM = ActiveDocument.Comments(1)
'set new selection for range to search
Dim rngWHERE As Range
Set rngWHERE = ActiveDocument.Range(0, COMM.Reference.Start)
rngWHERE.Select
Selection.Find.ClearFormatting
'set heading style name you applied>>
Selection.Find.Style = ActiveDocument.Styles("Nagłówek 1")
With Selection.Find
.Text = ""
.Replacement.Text = ""
.Forward = False
.Wrap = wdFindContinue
.Format = True
End With
Do While Selection.Find.Execute
If Selection.End < COMM.Reference.Start And _
Selection.Start > rngWHERE.Start Then
Set rngWHERE = Selection.Range
Else
Exit Do
End If
Loop
'select the range
rngWHERE.Select
'range selected is last heading
MsgBox "last heading befor comment is selected and it is: " & Selection.Text
End Sub
工作原理:
答案 1 :(得分:0)
引用会使用该答案中的技巧将您带到当前标题(如果有的话):Text of the preceding heading in word
Dim COMM As Comment
Set COMM = ActiveDocument.Comments(1)
Dim heading As Range
Set heading = COMM.Reference.GoTo(What:=wdGoToHeading, Which:=wdGoToPrevious)
' Display heading text
heading.Expand Unit:=wdParagraph
MsgBox heading.Text
现在,如果你想要整个关卡:
Dim headingLevel As Range
' headingLevel encompasses the region under the heading preceding COMM
Set headingLevel = COMM.Reference.GoTo(What:=wdGoToBookmark, Name:="\HeadingLevel")