使用Word文档中找到的字符串查找/替换文本

时间:2014-11-27 02:10:21

标签: vba word-vba

我一直试图修改给出here的精彩例子但收效甚微。在MSWord文档中,我需要能够找到<<TEST>>之类的文本,并恢复在<<>>之间找到的字符串,该字符串将返回TEST。最终,我打算使用它来查找TEST的值并返回要在Word文档中替换的字符串。即。例如,<<TEST>>变为FRED

Sub Sample()
    Dim c As Range
    Dim StartWord As String, EndWord As String, TheWord As String

    StartWord = "<<": EndWord = ">>"

    Set c = ActiveDocument.Content
    c.Find.ClearFormatting
    c.Find.Replacement.ClearFormatting
    With c.Find
        .Text = "[\<]{2}*[\>]{2}"
        '.Replacement.Text = TheWord
        .Forward = True
        .Wrap = wdFindStop
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = True
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With

    c.Find.Execute
    While c.Find.Found
        Debug.Print c.Text
        TheWord = Replace(Replace(c.Text, StartWord, ""), EndWord, "")
        Debug.Print TheWord
        c.Find.Replacement.Text = TheWord
        ' Future something here to lookup value based on 'TheWord'
        c.Find.Execute Replace:=wdReplaceOne
    Wend
End Sub

目前,我只是想替换像<<TEST>>这样的单词,这些单词可以在其中找到的字符串中找到。虽然它会找到并替换匹配模式的文本的第一个实例,但它找不到像example那样的其他文本。

感谢。

1 个答案:

答案 0 :(得分:0)

即使有时建议您不要在代码中使用Selection,我也希望在运行find >> replace操作时使用它。

在以下代码中,您将找到两个解决方案 - 第一个是用<< >>括号内的一个替换文字,第二个是替换为任何文本。不要同时运行两个,注释一个运行另一个。

Sub Sample()
    Dim c As Range
    Dim StartWord As String, EndWord As String, TheWord As String

    StartWord = "<<": EndWord = ">>"

    ActiveDocument.Range(0, 0).Select
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting

    With Selection.Find
        .Text = "[\<]{2}(*)[\>]{2}"
        .Replacement.Text = "\1"
        .Forward = True
        .Wrap = wdFindStop
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = True
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With

    'DO NOT RUN BOTH OPTIONS TOGETHER, CHOOSE ONE

    'OPTION 1. replace to inside text
    'Selection.Find.Execute Replace:=wdReplaceAll


    'OPTION 2. replace to any text, here- inside text found with replace function
    Do While Selection.Find.Execute

        Debug.Print Selection.Text
        TheWord = Replace(Replace(Selection.Text, StartWord, ""), EndWord, "")
        Debug.Print TheWord
        Selection.Text = TheWord
        Selection.Collapse WdCollapseDirection.wdCollapseEnd

    Loop
End Sub