基于多种样式搜索/提取文本

时间:2012-05-16 22:16:47

标签: vba word-vba

我有一个Word文档,其中的文本块标有称为“Princple”和“BusinessRule”的样式。这些文本块分散在整个文档中。我想按照它们出现的顺序找到并将这些块复制到单独的文档中。我正在使用的代码是:

Dim SelStyle As String
'SelStyle = "Principle"
SelStyle = "BusinessRule"


Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
    .Text = ""
    .Replacement.Text = ""
    .Style = SelStyle
    .Forward = True
    .Wrap = wdFindContinue
    .Format = True
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = True
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With
Selection.Find.Execute

Selection.Copy
Windows("Document1").Activate
Selection.TypeParagraph
Selection.PasteAndFormat (wdFormatPlainText)
Selection.TypeParagraph
Windows("mainDoc.docx").Activate
Selection.MoveRight Unit:=wdCharacter, Count:=1

如您所见,这是一个手动过程:首先取消注释原则,提取所有这些,然后注释Princple并取消注释BusinessRule。不是很好。有没有办法搜索.Style =“Principle”或.Style =“BusinessRule”所以我按顺序搜索它们? (其次,如果你有建议循环整个文件来做这件事,我会非常感激。: - ))

谢谢 - 比尔

2 个答案:

答案 0 :(得分:0)

为什么不将值存储在数组中?

Sub Sample()
    Dim SelStyle(1) As String

    SelStyle(0) = "Principle"
    SelStyle(1) = "BusinessRule"

    For i = 0 To 1
        Selection.Find.ClearFormatting
        Selection.Find.Replacement.ClearFormatting
        With Selection.Find
            .Text = ""
            .Replacement.Text = ""
            .Style = SelStyle(i)

        '
        '~~> Rest of your code
        '
    Next i
End Sub

答案 1 :(得分:0)

fwiw,我改变了我的方法。我没有搜索样式,而是浏览文档中的每个段落,看看样式是“原理”还是“BusinessRule”。如果为true,则复制/粘贴段落。因此,我不仅得到“或”,而且我也按顺序得到它们。