在多条件Word VBA中检索段落文本



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

查找所有"标题2"样式的段落,如果这些标题没有措辞";Notes";然后将某种风格应用于紧接着的段落。

这是我的代码:

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

然而,这些段落的措辞是";Notes";不排除在该过程之外,因此遵循它们的那些也被转换为样式";"正常";。我甚至不确定oPara。范围文本实际上检索段落的措辞。

谢谢。

我同意Timothy的观点。以下内容更快速、更简单。它也更可靠,因为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

这样尝试:

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"时,必须删除回车。

查找"Heading 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

最新更新