如何在excel中查找包含给定子字符串的单元格中的所有字符串

时间:2014-10-08 16:51:30

标签: excel

在Excel工作表中,每个单元格包含多个字符串。我想找到包含给定子字符串的所有字符串。在另一个单元格中打印包含子字符串的所有字符串的公式是什么?

例如:

  A1-> india china japan

  In A2, i have to print the strings that contains the substring "in" in A1

  A2-> india china

2 个答案:

答案 0 :(得分:1)

作为替代方案,您可以使用此UDF:

Public Function GETMATCHES(ByVal strOriginal As String, ByVal strMatch As String) As String

    GETMATCHES = Join(Filter(Split(WorksheetFunction.Trim(strOriginal), " "), strMatch), " ")

End Function

然后在单元格A2中将是这个公式:=GETMATCHES(A1,"in")

答案 1 :(得分:0)

我担心你不能用标准的Excel工作表函数做到这一点。您必须在VBA中为此编写自己的宏。

Function matches(ByRef rngCell As Range, ByVal strSearch As String) As String
    Dim astrWords As Variant
    Dim strWord As Variant
    Dim strResult As String

    'Get the value from the cell and split into words based on the space seperator
    astrWords = Split(CStr(rngCell.Value), " ")
    strResult = ""

    'Loop through the words and check if it contains the string that is searched for
    For Each strWord In astrWords
        If InStr(strWord, strSearch) Then
            'Add it to the result if a match is found
            If strResult <> "" Then
                'Add a space when a previous match was found
                strResult = strResult & " "
            End If
            strResult = strResult & strWord
        End If
    Next strWord
    'Return the result
    matches = strResult
End Function

作为示例,您可以将单元格A2中的函数用作

=matches(A1;"in")