Excel VBA对比A、B两列数据,将分类结果输出到C、D、E列
VBA两列对比分类输出代码
你原有代码仅实现了「提取A列独有的值输出到D列」的部分逻辑,我在你原有字典实现的基础上做了补全,完整覆盖三类结果的输出需求,保留了原代码无需手动引用库、运行效率高的特点。
输出规则对应
- C列:仅在A列存在、B列无匹配的值
- D列:仅在B列存在、A列无匹配的值
- E列:A、B两列同时存在的共有值
完整代码
Sub Compare1() 'Excel VBA to compare 2 lists. Dim ar As Variant Dim varAOnly(), varBOnly(), varCommon() Dim i As Long, nA As Long, nB As Long, nCommon As Long, lastRow As Long Dim Key As Variant ' 自动识别A、B列最大有效行数,避免漏读长列数据 lastRow = Cells(Rows.Count, "A").End(xlUp).Row If Cells(Rows.Count, "B").End(xlUp).Row > lastRow Then lastRow = Cells(Rows.Count, "B").End(xlUp).Row End If ar = Range("A1:B" & lastRow).Value ' 初始化三个结果数组,最大容量和数据行数一致 ReDim varAOnly(1 To lastRow, 1 To 1) ReDim varBOnly(1 To lastRow, 1 To 1) ReDim varCommon(1 To lastRow, 1 To 1) With CreateObject("scripting.dictionary") .CompareMode = 1 ' 文本对比不区分大小写,需要区分可改成0 ' 先将B列所有非空值存入字典 For i = 1 To UBound(ar, 1) If Trim(ar(i, 2)) <> "" Then .Item(ar(i, 2)) = "B" Next ' 遍历A列,区分共有值和A列独有值 For i = 1 To UBound(ar, 1) If Trim(ar(i, 1)) = "" Then GoTo SkipA If .Exists(ar(i, 1)) Then ' 值在两列都存在,归入共有结果 nCommon = nCommon + 1 varCommon(nCommon, 1) = ar(i, 1) .Item(ar(i, 1)) = "Both" ' 标记为已匹配,排除出B列独有结果 Else ' 值仅在A列存在 nA = nA + 1 varAOnly(nA, 1) = ar(i, 1) End If SkipA: Next ' 遍历字典剩余项,提取仅在B列存在的值 For Each Key In .Keys If .Item(Key) = "B" Then nB = nB + 1 varBOnly(nB, 1) = Key End If Next End With ' 清空C-E列旧数据后输出结果 Columns("C:E").ClearContents If nA > 0 Then [C1].Resize(nA).Value = varAOnly If nB > 0 Then [D1].Resize(nB).Value = varBOnly If nCommon > 0 Then [E1].Resize(nCommon).Value = varCommon End Sub
使用说明
- 代码默认对比当前活动工作表的A、B列数据,从第1行开始读取
- 自动跳过空单元格,不会把空值计入对比结果
- 输出前会自动清空C、D、E列的旧内容,避免历史数据干扰
- 测试示例:A列依次为1、2、3、5,B列依次为4、1、2、3时,运行后C列输出5,D列输出4,E列输出1、2、3,和需求效果完全一致
- 如果需要区分大小写对比,把代码里
.CompareMode = 1改成.CompareMode = 0即可
内容的提问来源于stack exchange,提问作者arush saxena
相关产品推荐
相关产品推荐

