比较2个单元格并在Excel中查找缺失的值

时间:2016-08-15 17:05:12

标签: excel vba sorting

我目前正在比较2个手动输入邮政编码的数据库。我需要比较每个数据库中数百个帐户的邮政编码,以检查是否缺少任何内容。我已经在excel中按升序排序了所有值,但似乎找不到快速检查缺少的内容。

Column A: Database A ZIPS (The correct ZIPs)
14464, 14515, 14612, 14615, 14626

Column B: Database B ZIPS (Manually Entered)
14464, 14612, 14615, 14626

Column C: Missing ZIPs
14515
编辑:我应该澄清一下,数据是以这种方式存储的。每个zip都没有存储在一个单独的列中,每个代理都有多个Zips。

Image of worksheet

我知道必须有一种方法可以使用excel VBA找到这个值!

由于

1 个答案:

答案 0 :(得分:0)

放手一搏 Public Function ShowMissingZips(rngSource As Range, _ rngMatch As Range) As String Dim colSource As Collection Dim colMatch As Collection Dim colOutput As Collection Dim varSource As Variant Dim varMatch As Variant Dim varOutput As Variant Dim intCounter As Integer Dim blnMatched As Boolean Dim strSource As String Dim strMatch As String Dim strOutput As String

Set colSource = New Collection
Set colMatch = New Collection
Set colOutput = New Collection

strSource = Replace(rngSource.Value, " ", "")
For Each varSource In Split(strSource, ",")
    colSource.Add varSource
Next

' Clean up source data
strMatch = Replace(rngMatch.Value, " ", "")
For Each varSource In Split(strMatch, ",")
    colMatch.Add varSource
Next

' Clean up match data    
For Each varSource In colSource
    blnMatched = False
    For Each varMatch In colMatch
        If varSource = varMatch Then
            blnMatched = True
            Exit For
        End If
    Next

    ' Note if it's not matched
    If Not blnMatched Then
        colOutput.Add varSource
    End If
Next

' Only output if there's anything present
If colOutput.Count > 0 Then
    For Each varOutput In colOutput
        strOutput = strOutput & CStr(varOutput) & ", "
    Next

    strOutput = Left$(strOutput, Len(strOutput) - 2)
End If

ShowMissingZips = strOutput

Set colSource = New Collection Set colMatch = New Collection Set colOutput = New Collection strSource = Replace(rngSource.Value, " ", "") For Each varSource In Split(strSource, ",") colSource.Add varSource Next ' Clean up source data strMatch = Replace(rngMatch.Value, " ", "") For Each varSource In Split(strMatch, ",") colMatch.Add varSource Next ' Clean up match data For Each varSource In colSource blnMatched = False For Each varMatch In colMatch If varSource = varMatch Then blnMatched = True Exit For End If Next ' Note if it's not matched If Not blnMatched Then colOutput.Add varSource End If Next ' Only output if there's anything present If colOutput.Count > 0 Then For Each varOutput In colOutput strOutput = strOutput & CStr(varOutput) & ", " Next strOutput = Left$(strOutput, Len(strOutput) - 2) End If ShowMissingZips = strOutput

要使用它,请按Alt-F11进入VBA编辑器。在项目资源管理器中找到您的工作簿(如果不可见,则按Ctrl-R),然后在顶部的菜单上单击插入...,模块。

粘贴此代码。

返回到您的工作簿并假设您像以前一样保留了列(A,B& C,第2行作为第一个数据行),转到单元格C2并键入

End Function

你应该看到你在追求什么。它不漂亮,我通常会添加错误处理,但它可以快速修复。

保存时,请务必使用XLSM格式(Excel 2007+)以保留VBA。