Solved

How to create a vba code to search a string for values on a list and return with the value found?

Posted on 2014-12-09
3
200 Views
Last Modified: 2014-12-10
I uploaded an example file with 4 different text strings in column “A” and the desired result in column “B” on sheet1.  The list of values to search for is found in cells on sheet2.
Exampe.xlsx
0
Comment
Question by:kbay808
  • 2
3 Comments
 
LVL 27

Accepted Solution

by:
Glenn Ray earned 500 total points
ID: 40490094
Here is a user-defined function that will work exactly as you requested:
Public Function Find_Matches(Test_Cell As Range, Lookup_array As Range) As String
    'This returns all substring matches within a cell
    Dim cl As Object
    For Each cl In Lookup_array
        If InStr(1, Test_Cell, cl.Value, vbTextCompare) > 0 Then
            Find_Matches = Find_Matches & cl.Value & ", "
        End If
    Next cl
    If Find_Matches <> "" Then
        Find_Matches = Left(Find_Matches, Len(Find_Matches) - 2)
    Else
        Find_Matches = "NOT FOUND"
    End If
End Function

Open in new window


In cell B2 you would enter:
=find_matches(A2,Sheet2!$A$2:$A$5)

and you could then copy that to each cell below.  

If more than one match is found, they are all shown - separated by commas.

Regards,
-Glenn
0
 

Author Closing Comment

by:kbay808
ID: 40490528
Perfect!!!  Thank you very much.
0
 
LVL 27

Expert Comment

by:Glenn Ray
ID: 40491700
You're welcome.  You'd be surprised how often I use this UDF myself.

-Glenn
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

A little background as to how I came to I design this code: Around 5 years ago I designed an add-in that formatted Excel files to a corporate standard, applying different cell colours and font type depending on whether the cells contained inputs,…
Introduction This Article briefly covers methods of calculating the NPV and IRR variants in Excel as well as the limitations in calculating and interpreting IRR results. Paraphrasing Richard Shockley, author of my favourite finance reference tex…
The viewer will learn how to use a discrete random variable to simulate the return on an investment over a period of years, create a Monte Carlo simulation using the discrete random variable, and create a graph to represent the possible returns over…
This Micro Tutorial will demonstrate how to use longer labels with horizontal bar charts instead of the vertical column chart.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now