Reputation: 125
This is the second time I've been using VBA/Excel in 10 years and it has not been a fun return. I'm trying to do something very simple, but I'm not sure if my datatypes are wrong or what, the debugger is not giving me much to go on. The execution fails in the cell where I use my custom function with the #VALUE! error. This makes me think my datatypes are invalid but I've referenced several different sources and cannot find what the issue is.
The function should search the Description cell text for any match of any substring stored in the Lookup1 range, then use the lookup2 range to do a hash-table style translation if it's found.
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
The only type issue I'm still unsure about is the txt = SubjCell.Value
. When I try to use SubjCell.Text
, the IDE de-capitalizes it to text
... Not sure why.
Upvotes: 2
Views: 7043
Reputation: 149295
Try this (Both work - TRIED AND TESTED)
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
Which is the same as
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
EDIT
SNAPSHOT
Upvotes: 2