Excel Example as I can't post picturesVBA Excel - 如何刪除基於兩列的重複
我已經上傳了一些示例的excel圖像。 我需要的是:
- 行3和4是重複的,但行4有「Dir」列中的數據。在這種情況下,同時刪除
- 第12行和第13行是重複的,「Dir」列中沒有數據。在這種情況下,只留下一排
我用條件格式突出複製並使用「IF」,「COUNTIF」 ......但沒有運氣,不知道如何完成這件事。
Excel Example as I can't post picturesVBA Excel - 如何刪除基於兩列的重複
我已經上傳了一些示例的excel圖像。 我需要的是:
我用條件格式突出複製並使用「IF」,「COUNTIF」 ......但沒有運氣,不知道如何完成這件事。
如果你想有一個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
謝謝戴維,但是當我運行宏時,它給出了一個錯誤「currentCell = Range(」A「&i).value」 –
這是什麼錯誤?你只是告訴我失敗的路線?你的Excel表格中有標題嗎?什麼是Range(「A」&i).value失敗時的值(在「Immediate Windows」中爲DEBUG.PRINT RANGE(「A」&i).VALUE –
錯誤是「運行時錯誤」6 ':Overflow',當我調試它時,我指向上面的行,它有標題。 –
Aaaaand你到目前爲止試過了什麼? – m02ph3u5
這可能有所幫助:http://stackoverflow.com/help/how-to-ask – newguy
我只有'ActiveSheet.Range(「A1:C」&K).RemoveDuplicates Columns:= 1,Header:= xlYes'K是一個字符串 –