Excel根据连续的匹配字符确定两个单元格是否匹配

时间:2018-11-16 20:00:26

标签: excel string character match partial

如何在两个单元格之间进行部分字符串匹配,其中部分字符串可以位于单元格中的任何位置。

示例:单元1可能具有AXG58934x0,单元2可能具有05893400 或单元1可能具有5893400A,而单元2可能具有X1000000589340000y 单元格应该在“ 58934”部分匹配。

希望Excel查看单元格1和单元格2,如果它找到字符上的匹配项,则查看下一个字符;如果匹配,则查看下一个字符;如果5个连续字符匹配,则返回单词“ match” ”。

2 个答案:

答案 0 :(得分:1)

[VBA解决方案]要实施:

  1. Alt + F11 打开Visual Basic
  2. VBAProject浏览器中找到您正在处理的书
  3. 右键单击并选择Insert Module
  4. 将以下代码粘贴到代码空间中
  5. 回到excel,您可以像调用任何函数=CSTMATCH()一样调用该函数

该函数需要2个输入(第一个字符串和第二个字符串),如下图所示


Option Explicit

Public Function CSTMatch(Target1 As Range, Target2 As Range) As Boolean

CSTMatch = False
Dim String1 As String, String2 As String, i As Long

'The goal here is to assign the larger String to the variable String1
If Len(Target1) >= Len(Target2) Then
    String1 = Target1
    String2 = Target2
Else
    String1 = Target2
    String2 = Target1
End If

For i = 1 To Len(String1) - 4
    If Mid(String1, i, 5) <> "00000" Then
        If InStr(String2, Mid(String1, i, 5)) Then
            CSTMatch = True
            Exit Function
        End If
    End If
Next i

End Function

UDF的输入/输出示例如下

enter image description here

答案 1 :(得分:1)

受@urdearboy启发

这将为您提供最短字符串中连续字符与最长字符串中连续字符的比率

Option Explicit

Public Function CSTMatch2(Target1 As Range, Target2 As Range) As Double

CSTMatch2 = 0

Dim String1 As String, String2 As String, i As Long, j As Long, noChar As Long

noChar = 0

'The goal here is to assign the larger String to the variable String1
If Target1 = Target2 Then
    CSTMatch2 = 1
    Exit Function
End If

If Len(Target1) >= Len(Target2) Then
    String1 = Target1
    String2 = Target2
Else
    String1 = Target2
    String2 = Target1
End If

For j = 1 To Len(String2)
    For i = 1 To Len(String1) - j
        If InStr(String2, Mid(String1, i, j)) Then
            noChar = noChar + 1
            Exit For
        End If
    Next i
Next j

Debug.Print noChar, Len(String1), Len(String2)
CSTMatch2 = (noChar) / (Len(String1))


End Function

样本: enter image description here