VBA返回2个字符串单元之间的差异

时间:2018-07-24 19:29:30

标签: excel-vba

我想做一个VBA UDF,它返回2个包含以逗号分隔的字符串的单元格之间的所有差异。它需要双向工作,而不取决于顺序。让我解释一下:

示例1

单元格N2:“ C1,C2,C3”

O2单元格:“ C2,C3”

或(反之亦然)

单元格N2:“ C2,C3”

O2单元格:“ C1,C2,C3”

我希望M2显示:“ C1”

示例2

单元格N2:“ C1,C2, C4 ,C5, C6 ”;

单元格O2:“ C1,C2,C5, C7

反之亦然

我希望M2显示:“ C4,C6,C7”(我不在乎显示差异的顺序)

我希望您能理解其中的所有内容,但任何区别都需要显示,但是如果唯一的区别是顺序,则什么都不应显示。

1 个答案:

答案 0 :(得分:1)

尝试此UDF

Sub Test_Difference_UDF()
MsgBox Difference("C1, C2, C3", "C11, C2, C3, C4")
End Sub

Function Difference(txt1 As String, txt2 As String) As String
Dim x           As Variant
Dim y           As Variant
Dim f           As Boolean
Dim s           As String
Dim i           As Long
Dim j           As Long

If InStr(txt1, ", ") > 0 And InStr(txt2, ", ") > 0 Then
    x = Split(txt1, ", ")
    y = Split(txt2, ", ")

    For i = LBound(x) To UBound(x)
        f = False
        For j = LBound(y) To UBound(y)
            If x(i) = y(j) Then f = True
        Next j
        If Not f Then s = s & IIf(s = "", "", ", ") & x(i)
    Next i

    For j = LBound(y) To UBound(y)
        f = False
        For i = LBound(x) To UBound(x)
            If y(j) = x(i) Then f = True
        Next i
        If Not f Then s = s & IIf(s = "", "", ", ") & y(j)
    Next j
End If

Difference = s
End Function