首页 > 解决方案 > 替换字符串时如果没有找到错误(选择替换,查找替换)

问题描述

这是我在运行宏时收到的错误。当 find 函数通过实现 if 语句找不到我正在搜索的内容时,我想我已经解决了。不知怎的,它仍然无法正常工作......

如果我正在搜索的值在我的记录中不存在,我如何跳过查找/替换语句?

在此处输入图像描述

我的 VBA 代码:

Columns("D:D").Select
Set Example1 = Selection.Find(what:="Example One", LookIn:=xlFormulas, lookat:=xlPart, SearchOrder:=xlByRows)
If Not Example1 Is Nothing Then
Selection.Replace what:="Example One", Replacement:= _
    "Test One A", lookat:=xlPart, SearchOrder:=xlByRows _
    , MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False, _
    FormulaVersion:=xlReplaceFormula2
End If

Set Example2 = Selection.Find(what:="Example Two ", LookIn:=xlFormulas, lookat:=xlPart, SearchOrder:=xlByRows)
If Not Example2 Is Nothing Then
Selection.Replace what:="Example Two ", Replacement:= _
    "Test One B", lookat:=xlPart, SearchOrder:=xlByRows, MatchCase:= _
    False, SearchFormat:=False, ReplaceFormat:=False, FormulaVersion:= _
    xlReplaceFormula2
End If

标签: excelvba

解决方案


只是一件快速的事情:on error resume next。当出现错误时,这会跳转到下一行。不是最好的选择,但在这段代码中它可能会有所帮助


推荐阅读