Excel /如何比较单元格中的字符

时间:2017-01-06 05:30:17

标签: excel vba excel-vba compare cells

我想比较单元格中的字符并返回剩余字符。例如,

A1 =(111,222,444,555)

B1 =(111,222,333,444,555,666)

然后,我想在单元格C1中看到遗骸,

C1 =(333,666)

有什么方法可以用excel功能吗?我是否必须使用VBA代码执行此操作?提前谢谢!

1 个答案:

答案 0 :(得分:1)

基于@Tim的评论,一个可能的UDF可能看起来像这样。

Public Function GetDiff(rngFirst As Range, rngSecond As Range) As String

    Dim arrFirst
    Dim arrSecond

    Dim lRctr1 As Long
    Dim lRctr2 As Long

    Dim bMatch      As Boolean
    Dim strResult   As String

    arrFirst = Split(IIf(Len(rngFirst) >= Len(rngSecond), rngFirst, rngSecond), ",")
    arrSecond = Split(IIf(Len(rngFirst) <= Len(rngSecond), rngFirst, rngSecond), ",")

    For lRctr1 = LBound(arrFirst) To UBound(arrFirst)
    bMatch = False
        For lRctr2 = LBound(arrSecond) To UBound(arrSecond)
            If (arrFirst(lRctr1) = arrSecond(lRctr2)) Then
                lRctr2 = UBound(arrSecond) + 1
                bMatch = True
            End If
        Next

        If Not bMatch Then
            strResult = strResult & arrFirst(lRctr1) & ","
        End If
    Next

    If Len(strResult) > 0 Then
        strResult = Mid(strResult, 1, Len(strResult) - 1)
    End If

    GetDiff = strResult

End Function

只需在模块中添加上面的代码,然后就可以使用它,比如说单元格C1 =GetDiff(A1,B1)