2016-03-14 36 views
0

Excel Example as I can't post picturesVBA Excel - 如何刪除基於兩列的重複

我已經上傳了一些示例的excel圖像。 我需要的是:

  • 行3和4是重複的,但行4有「Dir」列中的數據。在這種情況下,同時刪除
  • 第12行和第13行是重複的,「Dir」列中沒有數據。在這種情況下,只留下一排

我用條件格式突出複製並使用「IF」,「COUNTIF」 ......但沒有運氣,不知道如何完成這件事。

+1

Aaaaand你到目前爲止試過了什麼? – m02ph3u5

+0

這可能有所幫助:http://stackoverflow.com/help/how-to-ask – newguy

+0

我只有'ActiveSheet.Range(「A1:C」&K).RemoveDuplicates Columns:= 1,Header:= xlYes'K是一個字符串 –

回答

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"))

拖拽然後過濾「刪除」並刪除可見單元格。

enter image description here

+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 
+0

謝謝戴維,但是當我運行宏時,它給出了一個錯誤「currentCell = Range(」A「&i).value」 –

+0

這是什麼錯誤?你只是告訴我失敗的路線?你的Excel表格中有標題嗎?什麼是Range(「A」&i).value失敗時的值(在「Immediate Windows」中爲DEBUG.PRINT RANGE(「A」&i).VALUE –

+0

錯誤是「運行時錯誤」6 ':Overflow',當我調試它時,我指向上面的行,它有標題。 –