Word 2010 VBA - 嵌套直到...循环搜索和替换

时间:2015-05-01 07:58:58

标签: vba search replace ms-word

我尝试创建一个嵌套的Do Until ...循环,它将在Word文档中执行15种不同的搜索和替换。我需要完成以下内容(最后的分号仅用于列表目的):

Search  space ^t; replace with ^t;
Search ^t space; replace with ^t;
search ^t^t; replace with ^t;
search ^t^p; replace with ^p;
search $^t; replace with $;
search $ space; replace with $;
search ^t%; replace with %;
search space %; replace with %;
search (^t; replace with (;
search ( space; replace with (;
search ^t); replace with );
search space ); replace with );
search space ^p; replace with ^p;
search ^p space; replace with ^p; and
search ^p^p; replace with ^p.

我已经录制了宏,想要编辑它,取代众多     Selection.Find.Execute替换:= wdReplaceAll 在宏中每次搜索/替换时都会发生这种情况,直到结果为0个实例。我知道Do Until ... Loop会使这个宏更有效率。请帮忙!

1 个答案:

答案 0 :(得分:0)

这些方面的内容至少应该让你开始:

Dim searches() As String
Dim replaces() As String

searches = Split("( , %", ",")
replaces = Split("(,%", ",")

Dim i As Integer
For i = LBound(searches) To UBound(searches)
    With Selection.Find
        Do
            .ClearFormatting
            .Text = searches(i)
            .Replacement.Text = replaces(i)
            .Execute Replace:=wdReplaceAll
        Loop While .Found
    End With
Next i

搜索字符串和替换字符串以逗号分隔,并且必须是相同数量的元素 - 为清楚起见,仅包含两个元素(它们在整个地方连接vbTab和vbCr时会很难看。) / p>