从前一个标题获取标题编号

时间:2012-12-20 10:56:37

标签: vba word-vba

Paul Beverley编写的这个Word宏在文档中添加注释并插入页面和行号。

Sub CommentAdd()
' Version 20.02.12
' Add a comment
' Ctrl-Alt-#
attrib1 = "PB: "
attrib2 = "PB: "

postText = ""
keepPaneOpen = False
addPageNum1 = True
addLineNum1 = True
addPageNum2 = True
addLineNum2 = True

highlightTheText = False
textHighlightColour = wdYellow
colourTheText = False
textColour = wdColorBlue

Set rng = Selection.Range
rng.Collapse wdCollapseEnd
rng.MoveEnd , 1
pageNum = rng.Information(wdActiveEndAdjustedPageNumber)  ' <<<<<----- This line
lineNum = rng.Information(wdFirstCharacterLineNumber)
If Selection.End <> Selection.Start Then
  If Right(Selection, 1) = Chr(32) Then Selection.MoveEnd wdCharacter, -1
  Set rng1 = Selection.Range
' Either highlight it ...
  myTrack = ActiveDocument.TrackRevisions
  ActiveDocument.TrackRevisions = False
  If highlightTheText = True Then Selection.Range.HighlightColorIndex _
       = textHighlightColour
' And/or change the text colour to red
  If colourTheText = True Then Selection.Font.Color = textColour
  ActiveDocument.TrackRevisions = myTrack
' Now add the comment
  Selection.Comments.Add Range:=Selection.Range
  If addPageNum1 = True Then attrib1 = attrib1 & "(p. " & _
       pageNum & ") "
  If addLineNum1 = True Then attrib1 = attrib1 & "(line " & _
       lineNum & ") "
  Selection.TypeText Text:=attrib1 & ChrW(8216) & ChrW(8217)
' Move back to between the close and open quotes
  Selection.MoveEnd wdCharacter, -1
' 'Paste' in a copy of the selected text
  Set rng2 = Selection.Range
  rng2.FormattedText = rng1.FormattedText
  rng2.Revisions.AcceptAll
  rng2.Start = rng2.End - 1
  If rng2.Text = Chr(13) Then rng2.Delete
' Move back past the close quote
  rng2.Start = rng2.End + 1
  If postText > "" Then
    rng2.InsertAfter Text:=postText
  Else
    rng2.InsertAfter Text:=" " & ChrW(8211) & " "
  End If
If keepPaneOpen = False Then ActiveWindow.ActivePane.Close
Else
  cmntText = attrib2
  If addPageNum2 = True Then cmntText = cmntText & _     ' <<<<<----- And this I guess
       "(p. " & pageNum & ") "
  If addLineNum2 = True Then cmntText = cmntText & _
       "(line " & lineNum & ") "
  Selection.MoveEnd , 1
  Selection.Comments.Add Range:=Selection.Range, Text:=cmntText
End If
End Sub

我一直在尝试(在Word的VB编辑器中)调整突出显示的行(此处后跟'&lt;&lt;&lt;&lt;&lt; ----- This line')以使宏获取并写入数字上一个标题而不是页码。这个想法是,如果用户选择一个字符串,宏将在其上方查找最接近的标题级别(h1,h2,h3等)并写入其编号。

示例:

1这是header1&gt;如果所选字符串恰好在此标题下,则写入“1”

1.2这是header2&gt;如果所选字符串恰好位于此标题下,则写入“1.2”

1.2.1这是header3&gt;如果所选字符串恰好在此标题下,则写入“1.2.1”

到目前为止,我已尝试使用这两个选项来替换粗体线,但无效(我已将“pageNum”重命名为“headerNum”):

' Option 1
headerNum = ActiveDocument.Styles("Heading")

' Option 2
headerNum = Selection.range = Styles("Heading")

我做错了什么?

任何帮助都将受到高度赞赏!!!

0 个答案:

没有答案