【问题标题】:Error if nothing found when replacing a string (selection replace, find replace)替换字符串时如果没有找到错误(选择替换,查找替换)
【发布时间】:2021-09-26 19:59:56
【问题描述】:

这是我在运行宏时收到的错误。我想我已经解决了当 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

【问题讨论】:

  • 替换值是否会产生无效的公式?
  • 错误出现在哪一行???
  • 顺便说一句 - FormulaVersionRange.Replace 的新参数,不出所料,documentation 尚未更新 :-)
  • 它发生在第一个 Selection.Replace(示例一)上。 @BigBen 这是什么意思?同样不,它不应该像以前那样创建无效的公式。只是现在我在另一个文件上使用了它,它找不到值,因此给出了错误
  • 其实是的,FormulaVersion 似乎导致了这个问题。

标签: excel vba


【解决方案1】:

FormulaVersion:=xlReplaceFormula2 似乎是这个问题的罪魁祸首。一旦我删除它,代码就会根据需要工作。此外,不需要On Error Resume Next

【讨论】:

【解决方案2】:

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

【讨论】:

  • 谢谢,我想这将是一个临时修复,直到我找到一个更永久的修复。
  • 也许你什么也没找到,答案是 false。我想我记得 find 会返回 true 或 false。
  • 这就是为什么我包含 if 语句来解决 if find 返回 false 而不是跳过它(因为如果找不到该字符串,Example1 将不返回任何内容)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-22
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
相关资源
最近更新 更多