简单的Excel VBA搜索和查找功能提供了#VALUE!错误

时间:2012-06-01 21:36:25

标签: excel vba excel-vba excel-2010

这是我10年来第二次使用VBA / Excel,但这并不是一次有趣的回归。我正在尝试做一些非常简单的事情,但我不确定我的数据类型是错误的还是什么,调试器不会让我继续下去。在我使用自定义函数#VALUE的单元格中执行失败!错误。这让我觉得我的数据类型无效,但我引用了几个不同的来源,无法找到问题所在。

该函数应在Description单元格文本中搜索Lookup1范围中存储的任何子字符串的任何匹配项,然后使用lookup2范围进行哈希表样式转换(如果找到)。

Function ExtractCategory(Description As String, Lookup1 As Range, _
Lookup2 As Range) As String

    Dim txt As String
    Dim SubjCell As Range

    For Each rRange In Lookup1
        SubjCell = rRange
        txt = SubjCell.Value

        If InStr(txt, Description) <> 0 Then
            ExtractCategory = Application.WorksheetFunction.Lookup(txt, _
            Lookup1, Lookup2)
            Exit For
        Else
            ExtractCategory = "Not Found"
        End If
    Next rRange
End Function

我唯一不确定的类型问题是txt = SubjCell.Value。当我尝试使用SubjCell.Text时,IDE会将其去除资本化为text ...不确定原因。

1 个答案:

答案 0 :(得分:2)

尝试这一点(两者都有效 - 经过测试和测试

Function ExtractCategory(Description As String, Lookup1 As Range, _
Lookup2 As Range) As String
    Dim rRange As Range

    For Each rRange In Lookup1
        If InStr(1, rRange.Value, Description) Then
            ExtractCategory = Evaluate("=lookup(" & rRange.Value & "," & _
            Lookup1.Address & "," & Lookup2.Address & ")")
            Exit For
        Else
            ExtractCategory = "Not Found"
        End If
    Next rRange
End Function

相同
Function ExtractCategory(Description As String, Lookup1 As Range, _
Lookup2 As Range) As String
    Dim rRange As Range

    For Each rRange In Lookup1
        If InStr(1, rRange.Value, Description) Then
            ExtractCategory = Application.WorksheetFunction.Lookup(rRange.Value, _
            Lookup1, Lookup2)
            Exit For
        Else
            ExtractCategory = "Not Found"
        End If
    Next rRange
End Function

编辑

<强>快照

enter image description here