如何通过MS Word宏查找多个段落属性

时间:2016-03-19 08:56:00

标签: vba ms-word word-vba

我有一个宏,可以找到段落一词的一些属性。我需要找到4行或更多行'使用宏的段落。

我试过这段代码:

If oPar.LineCount = LineCount + 4 Then

请参阅下面的整个代码:

Sub CheckKeepLinesTogether()
Application.ScreenUpdating = False
Const message As String = "Check Keep Lines Together"
Dim oPar As Paragraph
Dim oRng As Word.Range
Dim LineCount As Long

For Each oPar In ActiveDocument.Paragraphs
Set oRng = oPar.Range

With oRng
    With .Find
        .ClearFormatting
        .Text = "^13"
        .Execute
    End With

    Set oRng = oPar.Range

        If oPar.KeepTogether = False Then
        If oPar.LineCount = LineCount + 4 Then

            .Select
            Selection.Comments.Add Range:=Selection.Range
            Selection.TypeText Text:=message
            Set oRng = Nothing

        End If
      End If
    End With
 Next
 Application.ScreenUpdating = True
 End Sub

2 个答案:

答案 0 :(得分:3)

使用未注释的代码替换有缺陷的代码:

    'If oPar.LineCount = LineCount + 4 Then
    If oPar.Range.ComputeStatistics(wdStatisticLines) >= 4 Then

顺便说一下,您不需要设置Set oRng = oPar.Range两次。

答案 1 :(得分:1)

未经测试

Sub CheckKeepLinesTogether()
    Application.ScreenUpdating = False
    Const message As String = "Check Keep Lines Together"
    Dim oPar As Paragraph
    Dim oRng As Word.Range
    Dim LineCount As Long

    For Each oPar In ActiveDocument.Paragraphs
    Set oRng = oPar.Range

    With oRng
        With .Find
            .ClearFormatting
            .Text = "^13"
            .Execute
        End With
            If oPar.KeepTogether = False Then
            If oPar.Range.ComputeStatistics(wdStatisticLines) >= 4 Then
              Set oRng = oPar.Range
                oRng.Comments.Add Range:=oRng
                oRng.TypeText Text:=message
             Set oRng = Nothing
            End If
          End If
        End With
     Next
     Application.ScreenUpdating = True
     End Sub