Word Macro正好在文档

时间:2016-08-09 21:27:24

标签: vba ms-word

我的第一个挑战是在单词doc中自动标注标题。这段代码有效:

Sub Underline_Header()

Dim numOfParagraphs As Integer
numOfParagraphs = ActiveDocument.BuiltInDocumentProperties("NUMBER OF PARAGRAPHS")
Selection.HomeKey Unit:=wdStory
For x1 = 1 To numOfParagraphs

Selection.Paragraphs(1).Range.Select

char_count = Len(Selection.Paragraphs(1).Range)

If char_count < 50 Then
Selection.Font.Underline = True
End If

Selection.MoveDown Unit:=wdParagraph, Count:=1

Next x1


End Sub

但事实证明,如果文档是20页,则宏停止在第10页。如果10,则停止在5. 4,然后在第2页停止。

我尝试将代码更改为Unit:=wdStoryUnit:=wdDocument,但这不是解决方案。我也尝试将Selection.EndKey Unit:=wdStory添加到代码中,但我得到了相同的结果。

1 个答案:

答案 0 :(得分:2)

您可以将其简化为类似

的内容
Sub Underline_Headers()
    Dim p As Paragraph
    For Each p in ActiveDocument.Paragraphs
        If Len(p.Range.Text) < 50 Then
            p.Range.Font.Underline = True
        End If
    Next p
End Sub