【问题标题】:Select the result of replacement - Word Macro选择替换结果 - Word 宏
【发布时间】:2019-07-15 18:23:30
【问题描述】:

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

说,这是文字:‎\[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

【问题讨论】:

  • 问题是您使用的是wdReplaceAll。这不会移动到任何东西 - 它只是替换文档中匹配的所有内容。
  • @CindyMeister 我应该怎么做?删除 wdReplaceAll 可以解决问题吗?
  • 仅使用 Selection.Find.Execute 会得到 Run-time error 4605, the method or property is not available because the object is empty
  • 对不起,我在移动设备上,之前...改用wdReplaceOne,它将进行一次替换,将选择(或范围,如果使用Range,改为)那一点。我已经把它写成答案了

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


【解决方案1】:

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

改用wdReplaceOneSelection(或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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-20
    • 1970-01-01
    相关资源
    最近更新 更多