简体   繁体   中英

Compare duplicates between two columns

I have two columns, Column A and column B.

  1. I need to find all duplicates in column A.
  2. If there are duplicates in Column A then compare them with the value in column B.

参考下图

My VBA macro should list 2 as a duplicate but should not list 1 as a duplicate.Pls help

Assuming your keys are in column A and values in column B (both starting from row 1), add this formula ...

=IsDuplicate(A:B,A1,B1)

... to cell C1 .

This code should work ...

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

Given there are a few holes in your description, I've assumed the following ...

  • Finding the same value again for the given the key will return a FALSE for a duplicate. So that means you can have duplicate rows with the same key value pair and they will be classed as non-duplicates. Of course, that could be changed if need be.
  • It assumes that the order of the data dictates what the first value for a key is and therefore, what will be flagged as a duplicate. So, reordering the data will produce a different result.
  • They key is case sensitive, so if not numeric, it will not factor in case.
  • I've assumed you're happy with using a UDF and not a macro that spits the result to a new destination.
  • In the first parameter, you can reference the entire 2 columns as your data set, it will skip over a blank set of keys 10 consecutive times and then on the 11th, it will exit the loop.

I hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM