自定义Excel VBA函数在某些情况下返回错误,而不是在其他情况下

时间:2015-06-18 13:15:35

标签: excel vba excel-vba

我的函数应该检查单元格中的字符串,然后返回该字符串(如果存在),如果不存在则返回空字符串。前两个部分工作正常 - 它检查,并返回它存在的字符串,但如果字符串不存在,则返回错误(#value)。发生了什么事?

Function Keyword(cell As Range, word As String)
  'checks given cell for keyword, returns keyword if present
  If (WorksheetFunction.IsNumber(WorksheetFunction.Search(word, cell.Range("A1"), 1))) Then
     Keyword = word + ", "
  Else: Keyword = ""
  'returns empty string if not present
  End If
End Function

这样称呼:=关键字(H2,“LED”)

1 个答案:

答案 0 :(得分:0)

如果找不到您要查找的值,则会出现运行时错误,并且您的功能将失败。更容易使用InStr来搜索值:

If Instr(1, cell.Range("A1").Value, word, vbTextCompare) <> 0 Then Keyword = word & ", "