Home » excel » excel – Complex Vlookup/ VBA function or Macro Needed For "if contains text then vlookup"

excel – Complex Vlookup/ VBA function or Macro Needed For "if contains text then vlookup"

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a problem, http://goo.gl/i82eA this is sample data that I have with the required output. Currently I have a user defined function that is manually using many if statements to do the job but I want to be able to do something like a vlookup if it finds a certain color in a colum and return the colormap coresponding to it.

Or use like a filter function like filter all cells that contain Blue and give the destination cell with blue, and then run next filter with next value in an table of colors.

Color   ColorMap     Text             Required Output
blue    blue         Deep Blue Shoe   Blue (if Text contains blue return blue)
red     red          Deep red Shoe    red (if Text contains red return red) etc
tan     brown        Tan Shoe         brown
navy    blue         Navy Emp Shoe    blue
jade    green        Jade Shoe        green
plum    red          Plum Red Shoe    multicoloured (if Text contains more than 1 color return multicolored)

So input should be like 2 columns for the data to be looked up 1 column for searching and the 1 column is the destination column if its a function

function_name(lookup_text,lookup_table,destination)

Thanks in advance

ps: here is the code Im using now

Code:

Function Colormap(strVal As String) As String

If (InStr(strVal, "red") > 0) Then
    Colormap = "Red"
End If

If (InStr(strVal, "Beige") > 0) Then
    Colormap = "Beige"
End If

etc..

End Function
How to&Answers:

This looks up the Text value and returns the ColorMap value; if more than one match is found “multicolored” is returned. Note: This is an array formula–enter it with Ctrl+Shift+Enter.

=IF(SUM(IF(ISNUMBER(SEARCH(A$2:A$7,C2)),1,0))>1,"multicolored",LOOKUP(2^15,SEARCH(A$2:A$7,C2),B$2:B$7))

Here’s a function that does the same thing. It requires that the reference table be a named range. Call the function like this: =ColorMap(C2,"ColorTable") where ColorTable is a named range referring to $A$2:$B$7.

Public Function ColorMap(LookupValue As Variant, LookupTableName As String) As String
    Dim vTable As Variant
    Dim lIdx As Long
    Dim sColor As String

    ' transfer lookup table to 2D range & loop through to find matches
    vTable = Names(LookupTableName).RefersToRange.Value
    For lIdx = LBound(vTable, 1) To UBound(vTable, 1)
        If UCase$(LookupValue) Like "*" & UCase$(vTable(lIdx, 1)) & "*" Then
            sColor = sColor & ", " & vTable(lIdx, 2)
        End If
    Next lIdx
    If Len(sColor) > 2 Then sColor = Mid$(sColor, 3)
    ' map multiple matches to "multicolored"
    If InStr(sColor, ",") > 0 Then sColor = "multicolored"
    ColorMap = sColor
End Function