选择替换结果-Word宏

时间:2019-07-15 03:26:39

标签: vba ms-word full-text-search

我想要获取并选择“查找和替换”宏的结果,并对它进行一些操作。

说,这是文本:\[abc\]‎,我想将其转换为abc,然后选择abc

代码如下:

    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = "(\\\[)(*)(\\\])"
        .Replacement.Text = "\2"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchKashida = False
        .MatchDiacritics = False
        .MatchAlefHamza = False
        .MatchControl = False
        .MatchAllWordForms = False
        .MatchSoundsLike = False
        .MatchWildcards = True
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    Selection.Cut

在最后一行,Selection.Cut给出一个错误,表明选择为空。 我想选择替换的输出并剪切它。

从我的存储库Amin MSWord VBA macros

1 个答案:

答案 0 :(得分:1)

wdReplaceAll,因为替换“目标”不会跳到单个“命中”,这就是Selection没有拾取任何东西的原因。

使用wdReplaceOne代替,Selection(或Range对象,如果使用的话)将移至找到的内容。

您可能希望在发出.Cut命令之前测试是否确实找到了某些内容,因为如果什么也没找到(在启动宏的那一刻删除内容),可能会导致意外的结果。例如:

Sub FindReplaceAndCut()
    Dim found As Boolean

    With Selection.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Text = "(\\\[)(*)(\\\])"
        .Replacement.Text = "\2"
        .Forward = True
        .wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchKashida = False
        .MatchDiacritics = False
        .MatchAlefHamza = False
        .MatchControl = False
        .MatchAllWordForms = False
        .MatchSoundsLike = False
        .MatchWildcards = True
    End With
    found = Selection.Find.Execute(Replace:=wdReplaceOne)
    If found Then
        Selection.Cut
    End If
End Sub