比较两列之间的重复项

时间:2019-02-09 17:16:27

标签: excel vba

我有两列,即A列和B列。

  1. 我需要在A列中找到所有重复项。
  2. 如果A列中有重复项,则将它们与B列中的值进行比较。

refer below image

我的VBA宏应将2重复列出,但不应将1重复列出。请帮助

1 个答案:

答案 0 :(得分:0)

假设您的键在 A 列中,值在 B 列中(均从第1行开始),请添加此公式...

=IsDuplicate(A:B,A1,B1)

...到单元格 C1

此代码应该有效...

Public Function IsDuplicate(ByVal rngAllData As Range, ByVal strKey As String, ByVal strValue As String) As Boolean
    Dim lngBlanks As Long, objRow As Range, strThisKey As String, strThisValue As String, strFirstValue As String
    Dim bFound As Boolean

    Application.Volatile

    For Each objRow In rngAllData.Rows
        strThisKey = Trim(objRow.Cells(1, 1))
        strThisValue = Trim(objRow.Cells(1, 2))

        If strThisKey = "" Then
            lngBlanks = lngBlanks + 1
        Else
            lngBlanks = 0

            If strThisKey = strKey Then
                If Not bFound Then
                    strFirstValue = strThisValue

                    If strValue = strFirstValue Then
                        IsDuplicate = False
                        Exit Function
                    Else
                        bFound = True
                    End If
                Else
                    If strThisValue <> strFirstValue Then
                        IsDuplicate = True
                        Exit Function
                    End If
                End If
            End If
        End If

        If lngBlanks > 10 Then Exit For
    Next
End Function

鉴于您的描述中有一些漏洞,我假设以下内容...

  • 再次为给定的键查找相同的值,则对于重复项将返回FALSE。因此,这意味着您可以拥有具有相同键值对的重复行,并且它们将被归类为非重复行。当然,可以根据需要更改它。
  • 假定数据的顺序决定了键的第一个值是什么,因此,将其标记为重复项。因此,对数据重新排序将产生不同的结果。
  • 它们的键区分大小写,因此,如果不是数字,则不会考虑大小写。
  • 我假设您对使用UDF感到满意,而不是将结果吐到新目的地的宏。
  • 在第一个参数中,您可以引用整个两列作为数据集,它将连续10次跳过空白键集,然后在第11个参数中退出循环。

我希望有帮助。