【问题标题】:Compare two string values and return the common string比较两个字符串值并返回公共字符串
【发布时间】:2014-07-08 17:45:50
【问题描述】:

这就是我想在 Excel 中做的事情。

A1 = 你好,我叫约翰 B1 = 你好,我叫乔

C1 = 你好,我的名字是

A2 = 约翰明天要去哪里? B2 = 乔明天要去哪里?

C1 = 在哪里

如您所见,我想比较 2 个单元格并返回公共字符串,直到有差异为止。 (一有变化就停止比较)

我看到了类似的here,但它与我的要求略有不同。

提前致谢。

【问题讨论】:

  • -1 因为你没有表现出任何努力自己解决任务。
  • 不幸的是我不是这方面的专家,因此求助于这个论坛。事实上,这是我第一次在网上寻求帮助:-(

标签: excel function match string-comparison


【解决方案1】:

您应该寻找一种更有效的方法,但这是 VBA 中的一种:

Dim stringA As String
Dim stringB As String

Dim finalString As String

Dim currentLetter As Integer

For currentLetter = 0 To Len(stringA)
    If Left(stringA, currentLetter) = Left(stringB, currentLetter) Then
        finalString = Left(stringA, currentLetter)
        Exit For
    End If
Next

用你的单元格替换字符串变量就完成了。

【讨论】:

  • 不应该是:If Left(stringA, currentLetter) <> Left(stringB, currentLetter) Then 停止一切
【解决方案2】:

我喜欢这个挑战,所以我想出了一个公式解决方案:

=LEFT(A1,LOOKUP(2,1/(MID(LEFT(A1,MATCH(FALSE,INDEX(MID(A1,ROW($1:$99),1)=MID(B1,ROW($1:$99),1),),0)-1),ROW($1:$99),1)=" "),ROW($1:$99))-1)

【讨论】:

    【解决方案3】:

    这里的答案很好,只有一件事是错误的(至少对我而言)。我无法发表评论,因此我将解决方案与我的修复一起粘贴到此处。不需要“退出”:

    Dim stringA As String
    Dim stringB As String
    
    Dim finalString As String
    
    Dim currentLetter As Integer
    
    For currentLetter = 0 To Len(stringA)
        If Left(stringA, currentLetter) = Left(stringB, currentLetter) Then
            finalString = Left(stringA, currentLetter)            
        End If
    Next
    

    【讨论】:

      【解决方案4】:
      Sub CommonText()
          'Finds the longest substring that string A and string B have in common.
      
          sA = "Hey, My Name is John"
          sB = "My Name is Eric"
      
          Dim iLtrA As Integer
      
          Dim iLtrB As Integer
          Dim sThisString As String
          Dim sFinalString As String
      
          sFinalString = ""
      
          For iLtrA = 1 To Len(sA)
      
              For iLtrB = 1 To Len(sB)
      
                  For n = 1 To Application.Min(Len(sA), Len(sB))
                      'mid(text,start, length)
                      If Mid(sA, iLtrA, n) = Mid(sB, iLtrB, n) Then
                          sThisString = Mid(sA, iLtrA, n)
                          If Len(sThisString) >= Len(sFinalString) Then
                              sFinalString = sThisString
                          End If
                      End If
                  Next n
              Next iLtrB
          Next iLtrA
      
          Debug.Print sFinalString
      
      End Sub
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多