首页 > 解决方案 > Range.Find 在查找失败时产生错误

问题描述

这是两行简单的代码,用于在列表中查找 6 位数字的实例。如果数字存在,一切正常,但如果不存在,我会收到错误“对象变量或未设置块变量”

代码行是

    COL = Cells(5, "A").Text
    RowFound = Sheets("Master List").Columns("A").Find(What:=COL).Row

单元格格式为列中的文本和搜索数据单元格中的文本

对此的任何建议都会有所帮助并非常感谢

标签: excelvba

解决方案


这就是 VBA 的工作方式。VBA 不能从不存在的范围返回行。

请尝试下一个方法:

Sub testFindFail()
  Dim c As Range, RowFound As Long, COL As String
  COL = cells(5, "A").text
  Set c = Sheets("Master List").Columns("A").Find(What:=COL) 'it will be good to also use some other parameters.
  If c Is Nothing Then Exit Sub 'or do something else
  RowFound = c.row
  Debug.Print RowFound
End Sub

推荐阅读