找出Excel中两个文本单元格之间的差异

时间:2017-05-14 00:55:28

标签: excel formulas excel-2016

我有2个单元格,其中包含以逗号(,)分隔的数字列表。 K中的列表是完整集合,D中的列表是部分集合。我想将M中不属于K的部分加入D

示例:

K4 = 1,2,5,6

D4 = 1,5,6

结果M4 = 2

我使用了SUBSTITUTE,但这仅适用于D中的数字有序并且不会遗漏K中间的任何内容。

我需要一个非VBA答案。

2 个答案:

答案 0 :(得分:1)

如果您订阅了Office 365 Excel,则可以使用此数组公式:

=TEXTJOIN(",",TRUE,IF(ISNUMBER(SEARCH("," &TRIM(MID(SUBSTITUTE(K4,",",REPT(" ",999)),(ROW(INDIRECT("1:" & LEN(K4)-LEN(SUBSTITUTE(K4,",",""))+1))-1)*999+1,999))&",",","&D4&",")),"",TRIM(MID(SUBSTITUTE(K4,",",REPT(" ",999)),(ROW(INDIRECT("1:" & LEN(K4)-LEN(SUBSTITUTE(K4,",",""))+1))-1)*999+1,999))))

作为数组公式,需要在退出编辑模式时使用Ctrl-Shift-Enter而不是Enter来确认。如果正确完成,那么excel会将{}放在公式周围。

enter image description here

我知道你要求非vba答案,但是;

如果您没有订阅Office 365 Excel,可以将此代码放在工作簿附带的模块中,并使用上述公式。

Function TEXTJOIN(delim As String, skipblank As Boolean, arr)
    Dim d As Long
    Dim c As Long
    Dim arr2()
    Dim t As Long, y As Long
    t = -1
    y = -1
    If TypeName(arr) = "Range" Then
        arr2 = arr.Value
    Else
        arr2 = arr
    End If
    On Error Resume Next
    t = UBound(arr2, 2)
    y = UBound(arr2, 1)
    On Error GoTo 0

    If t >= 0 And y >= 0 Then
        For c = LBound(arr2, 1) To UBound(arr2, 1)
            For d = LBound(arr2, 1) To UBound(arr2, 2)
                If arr2(c, d) <> "" Or Not skipblank Then
                    TEXTJOIN = TEXTJOIN & arr2(c, d) & delim
                End If
            Next d
        Next c
    Else
        For c = LBound(arr2) To UBound(arr2)
            If arr2(c) <> "" Or Not skipblank Then
                TEXTJOIN = TEXTJOIN & arr2(c) & delim
            End If
        Next c
    End If
    TEXTJOIN = Left(TEXTJOIN, Len(TEXTJOIN) - Len(delim))
End Function

答案 1 :(得分:0)

这是一个适用于单个缺失值的公式。如果需要返回多个缺失值,可以使用辅助列,但VBA会更简单。通常输入公式,并且该公式应适用于大多数版本的Excel:

=LOOKUP(2,1/ISERR(SEARCH(TRIM(MID(SUBSTITUTE(K4,",",REPT(" ",99)),seq_99,99)),D4 & ",")),TRIM(MID(SUBSTITUTE(K4,",",REPT(" ",99)),seq_99,99)))

seq_99是一个定义的名称(在本例中为公式),它生成一个值数组{1,99,198,297, ...}

seq_99  Refers to:  =IF(ROW(INDEX($1:$65535,1,1):INDEX($1:$65535,255,1))=1,1,(ROW(INDEX($1:$65535,1,1):INDEX($1:$65535,255,1))-1)*99)

对于VBA例程,建议特别是如果可能有多个缺失项目,请尝试以下操作:

Option Explicit
Function MissingValues(sFull As String, sPartial As String) As String
    Dim RE As Object
    Dim sPat As String
    Dim S As String

'Replace commas with pipes, surround by brackets "[]" and follow by end
'  of line to create regex pattern from sPartial
sPat = "[" & Replace(sPartial, ",", "|") & "](?:,|$)"

Set RE = CreateObject("vbscript.regexp")
With RE
    .Pattern = sPat
    .ignorecase = True
    .Global = True
    .MultiLine = True
    S = .Replace(sFull, "")
    .Pattern = ",$"
    MissingValues = .Replace(S, "")
End With

End Function

例程使用正则表达式删除部分集中显示的完整集中的所有内容。 (然后最后检查删除任何终端逗号)。这将以相同的逗号分隔模式返回多个缺失值。它不区分大小写,但您可以看到可以轻松更改的位置。

这是一个屏幕截图,比较两个方法的输出,当有两个缺失值时:

enter image description here