简体   繁体   English

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

[英]Custom Excel VBA function returning error in some cases, not in other

My function is supposed to check a cell for a string, and then return that string if its present, and return an empty string if it's not. 我的函数应该检查一个单元格是否有字符串,然后返回该字符串(如果存在),否则返回一个空字符串。 The first two parts are working fine--it checks, and it returns the string it it's present, but if the string isn't present, it returns an error (#value). 前两个部分工作正常-检查并返回存在的字符串,但是如果不存在,则返回错误(#value)。 What's happening? 发生了什么?

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

Call it like this: =Keyword(H2,"LED") 这样命名:= Keyword(H2,“ LED”)

If the value you are looking for isn't found, you'll get run-time errors, and your function will fail. 如果找不到所需的值,则会出现运行时错误,并且功能将失败。 Easier to use InStr to search for the value: 使用InStr来搜索值更容易:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM