【问题标题】:Retrieving paragraph text in multiple conditions Word VBA在多个条件Word VBA中检索段落文本
【发布时间】:2021-03-05 22:42:23
【问题描述】:

在一个长的 Word 文档中,我想执行以下操作:

查找所有“标题 2”样式的段落,如果这些标题没有用“注释”措辞,则将某种样式应用于紧随其后的段落。

这是我的代码:

Dim oPara As Paragraph
    For Each oPara In ActiveDocument.Paragraphs
        If oPara.Style = "Heading 2" And oPara.Range.Text <> "Notes" Then
            oPara.Range.Next(Unit:=wdParagraph, Count:=1).Select
           Selection.Style = "Normal"
        End If
    Next oPara

但是,“注释”段落不排除在程序之外,因此后面的段落也会转换为“普通”样式。我什至不确定 oPara.Range.Text 是否真的检索了段落的措辞。

谢谢。

【问题讨论】:

    标签: vba ms-word multiple-conditions


    【解决方案1】:

    试试这样:

    Dim oPara As Paragraph
    
    For Each oPara In ActiveDocument.Paragraphs
        If oPara.Style = "Heading 2" And Replace(oPara.Range.Text, Chr(13), "") <> "Notes" Then
            oPara.Range.Next(Unit:=wdParagraph, Count:=1).Select
           Selection.Style = "Normal"
        End If
    Next oPara
    

    Word好像在表头文字后面加了一个回车Chr(13),所以在检查表头文字是否为"Notes"时,一定要把回车去掉。

    【讨论】:

      【解决方案2】:

      查找“标题 2”的所有实例的最有效方法是使用 Find。然后,您可以测试找到的范围的文本,如果它符合您的条件,则将样式应用于以下段落。

      Sub FormatAfterHeading()
         Dim findRange As Range
         Set findRange = ActiveDocument.Content
         With findRange.Find
            .ClearFormatting
            .Replacement.ClearFormatting
            .Text = ""
            .Style = ActiveDocument.Styles(wdStyleHeading2)
            .Forward = True
            .Format = True
            .Wrap = wdFindStop
            Do While .Execute = True
               If InStr(findRange.Text, "Notes") > 0 Then
                  'do nothing
               Else
                  findRange.Next(wdParagraph, 1).Style = wdStyleNormal
               End If
               findRange.Collapse wdCollapseEnd
            Loop
         End With
      End Sub
      

      【讨论】:

        【解决方案3】:

        我同意蒂莫西的观点。以下更快 - 更简单。它也更可靠,因为 Timothy 的代码匹配段落中任何位置的“Notes”,而不是“Notes”是整个​​段落文本。

        Sub Demo()
        Application.ScreenUpdating = False
        With ActiveDocument.Range
          With .Find
            .ClearFormatting
            .Replacement.ClearFormatting
            .Text = ""
            .Style = ActiveDocument.Styles(wdStyleHeading2)
            .Forward = True
            .Format = True
            .Wrap = wdFindStop
          End With
          Do While .Find.Execute = True
            If .Text <> "Notes" & vbCr Then .Next(wdParagraph, 1).Style = wdStyleNormal
            .Collapse wdCollapseEnd
          Loop
        End With
        Application.ScreenUpdating = True
        End Sub
        

        【讨论】:

        • 非常酷(我添加了缺少的 End If)。非常感谢,也感谢 sbgib 和 Timothy Rylatt 提供的有用解决方案。
        猜你喜欢
        • 2017-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多