【问题标题】:Compare two cells in excel and return the matching string length比较excel中的两个单元格并返回匹配的字符串长度
【发布时间】:2014-04-23 07:50:37
【问题描述】:

我需要在excel中比较两个相邻的单元格,并从最左边的字符开始返回两个单元格之间匹配的字符数

A和B列的值如下

A1 = Sam Alhoa
A2 = Franklin moore
A3 = Steve jones
A4 = Joe
A5 = Patrick

B1 = Sam Bloggs
B2 = Frank lin dsouza
B3 = Stephen Jones
B4 = Jose
B5 = Patrice

C 列的结果应该是

C1 = 4
C2 = 5
C3 = 3
C4 = 2
C5 = 6

执行此操作的 excel 公式是什么?

【问题讨论】:

    标签: excel excel-formula string-comparison string-matching vba


    【解决方案1】:

    你可以使用这个 UDF:

    Function compareCharacters(s1 As String, s2 As String) As Integer
        Dim i As Integer
    
        For i = 1 To Application.Min(Len(s1), Len(s2))
            If Mid(s1, i, 1) <> Mid(s2, i, 1) Then Exit Function
            compareCharacters = compareCharacters + 1
        Next
    End Function
    

    并像这样在任何单元格中调用它:

    =compareCharacters(A1,B1)
    

    【讨论】:

      【解决方案2】:

      试试这个:
      =SUM(IFERROR(IF(MID(A1,ROW(INDIRECT("$1:$" & LEN(A1))),1)=MID(B1,ROW(INDIRECT("$1:$" & LEN(B1))),1),1,0),0))

      使用 Ctrl+Shift+Enter 作为数组公式输入到 C1。

      【讨论】:

      • 据我了解,OP希望从左侧开始查找匹配字符的数量,例如对于字符串abcdeabcee,您的公式返回4,但似乎应该返回3(根据我对问题的理解)
      • @simoco haha​​ 我也很奇怪为什么你是Exit Function 而不是End If。 OP想要从左到右计算匹配字符的数量,但没有语句告诉停止计算第一个不匹配。 :)。我想让我们感到困惑的是第一项,如果你计算包括Space在内的匹配字符,它应该是5
      • 按照我的方法,比较Sam AlhoaSam Bloggs 得到4(如OP 示例),因为Sam (带空格)在两个字符串中。不考虑l,因为之前的字符AB不一样
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-23
      • 1970-01-01
      相关资源
      最近更新 更多