Excel: Return multiple matches in a single cell while doing a partial match

独自空忆成欢 提交于 2019-12-08 14:25:49

问题


I am working on a file that has two columns. The first column has simple three word sentences. The second one has single word keywords.

I’d like to be able search the first column, find all sentences that have a specific keyword and list them as delimited values next to the keyword.

Assuming a pipe (“|”) as a delimiter, I’d get something like this:

First Column
Very blue sky.
Red sky tonight. 
Blue sky forever. 
My red car. 
Red red red.

Second column is as follows:

Second Column
Blue
Red

Desired Solution (has 2 columns, Blue and Red are in the first column)

Second Column         Results Column
Blue                  Very blue sky. | Blue sky forever. 
Red                   Red sky tonight. | My red car. | Red red red.

Thanks!


回答1:


Here is one way of doing it.

  1. Open Visual Basic Editor (VBE) by pressing ALT+F11 key.
  2. Insert a new module using Insert >> Module
  3. Paste below code in the code pane.

    Public Function ConcatPartLookUp(rngInput As Range, rngSource As Range, Optional strDelimiter As String, Optional blCaseSensitive)
    Dim rng As Range
    
    If strDelimiter = "" Then strDelimiter = "|"
    If IsMissing(blCaseSensitive) Then
        blCaseSensitive = False
    Else
        blCaseSensitive = True
    End If
    
    For Each rng In rngSource
        If blCaseSensitive Then
            If InStr(1, rng.Value, rngInput.Value, vbBinaryCompare) > 0 Then ConcatPartLookUp = ConcatPartLookUp & strDelimiter & rng.Value
        Else
            If InStr(1, rng.Value, rngInput.Value, vbTextCompare) > 0 Then ConcatPartLookUp = ConcatPartLookUp & strDelimiter & rng.Value
        End If
    Next
    
    If Len(ConcatPartLookUp) > 0 Then ConcatPartLookUp = Mid(ConcatPartLookUp, 2, Len(ConcatPartLookUp))
    
    End Function
    

Then you can use this function in sheet like any other normal function e.g.

=ConcatPartLookUp(B2,A2:A6)

Please note I have provided two more optional arguments which may prove useful in the long run. If you want to make it case sensitive and pass a different delimiter say "#" then you need to use:

=ConcatPartLookUp(B2,A2:A6,"#",TRUE)



来源:https://stackoverflow.com/questions/46901262/excel-return-multiple-matches-in-a-single-cell-while-doing-a-partial-match

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!