VBA Excel - 如何根据两列删除重复项

时间:2016-03-14 14:47:08

标签: excel vba

Excel Example as I can't post pictures

我已经通过一些示例上传了excel的图片。 我需要的是:

  • 第3行和第4行是重复的,但第4行的数据是" Dir"柱。在这种情况下,删除两个
  • 第12行和第13行是重复的,没有数据在" Dir"柱。在这种情况下只留一行

我已使用条件格式来突出显示重复项并使用" IF" " Countif" ....但没有运气,也没有线索如何完成这项工作。

2 个答案:

答案 0 :(得分:0)

如果您需要VBA选项,则此代码将执行此操作:

  Option Explicit

Sub DeleteDupes()

    Dim workingRow As Long
    Dim workingItem As String
    Dim i As Long
    Dim occurances As Variant

    'Skip past header row
    workingRow = 1

    Do Until Range("A" & workingRow + 1).value = ""

        workingRow = workingRow + 1
        workingItem = Range("A" & workingRow).value

        If Len(Range("C" & workingRow)) = 0 Then

            occurances = FncGetOccurances(workingRow, workingItem)

            If IsArray(occurances) Then

                FncDeleteRange (occurances)
                workingRow = workingRow - UBound(occurances)

            End If

        End If

    Loop

End Sub

Private Function FncDeleteRange(value As Variant)

    Dim deleteRange As Range
    Dim i As Long

    For i = 1 To UBound(value)

            If i = 1 Then

                Set deleteRange = Range("A" & value(i), "C" & value(i))
                deleteRange.Select

            Else

                Union(deleteRange, Range("A" & value(i), "C" & value(i))).Select

            End If
    Next i

    Selection.Delete Shift:=xlUp

End Function

Private Function FncGetOccurances(masterIndex As Long, value As String) As Variant

    Dim rowsToReturn As Variant
    Dim i As Long
    Dim currentCell As Long
    Dim itemCount As Long

    i = 1

    Do While Range("A" & i + 1).value <> ""

        i = i + 1
        currentCell = Range("A" & i).value

        If currentCell = value And _
            i <> masterIndex And _
            Len(Range("C" & i)) <> 0 Then

            itemCount = itemCount + 1

            If itemCount = 1 Then

                ReDim rowsToReturn(itemCount)

            Else

                ReDim Preserve rowsToReturn(itemCount)

            End If

            rowsToReturn(itemCount) = i

        End If

    Loop

    FncGetOccurances = rowsToReturn

End Function

答案 1 :(得分:0)

对于基于公式的方法(使用辅助列,您可以执行以下操作:

  1. D2公式:=COUNTIFS($A$1:$A2,A2)
  2. E2公式:=COUNTIFS($A$2:$A$33,A2,$C$2:$C$33,"LD")
  3. F2公式:=IF(AND(COUNTIF($A$2:$A$21,A2)=1,E2=1),"Keep",IF(OR(AND(D2>0,E2>0),AND(D2>1,E2=0)),"Remove","Keep"))
  4. 向下拖动然后过滤“删除”并删除可见的单元格。

    enter image description here