I have written the following code to clear the dataset of duplicates if it meets a certain criteria (column E). It scans through 1216 lines of data (LastRow has 1216 hits) and clears the duplicates. Only issue I had was if I had two or three duplicates it would only delete one duplicate.
I wrote another line of code stating if a single item (column B) is found more than once that a variable called statement is equal to TRUE. So I want the loop to continue until no duplicates are present in the dataset, which will also turn the variable to FALSE and stop the loop. However, the loop continues endlessly. When I stop the script manually it seems to have cleared all the duplicates.
Sub ClearDataSet()
Dim LastRow As Integer
Dim i As Integer
Dim Rng, cell As Range
Dim Statement As Boolean
Set ws1 = ThisWorkbook.Worksheets("sheet1")
Set Rng = ws1.Range(("D1"), ws1.Range("D1").End(xlDown))
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
ws1.Range("A1").CurrentRegion.Sort _
key1:=ws1.Range("D1"), order1:=xlAscending, _
Key2:=ws1.Range("E1"), order2:=xlAscending, Header:=xlYes
Do
For i = 2 To LastRow
If ws1.Cells(i, "D") = ws1.Cells(i + 1, "D") And _
(ws1.Cells(i, "E") < ws1.Cells(i + 1, "E") Or _
ws1.Cells(i, "E") = ws1.Cells(i + 1, "E")) Then
Rows(i).Delete
End If
Next i
For Each cell In Rng
If WorksheetFunction.CountIf(Rng, cell.Value) > 1 Then
Statement = True
End If
Next cell
Loop Until Statement <> True
End Sub
EDIT: Tweaked (and more efficient) script after solution of M Schalk
Sub ClearDataSet()
Dim LastRow As Integer
Dim i As Integer
Dim Rng, cell As Range
Dim Statement As Boolean
Dim StartTime As Long
Dim TimeElapsed As Long
StartTime = Timer
Set ws1 = ThisWorkbook.Worksheets("sheet1")
Set Rng = ws1.Range(("D1"), ws1.Range("D1").End(xlDown))
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
ws1.Range("A1").CurrentRegion.Sort _
key1:=ws1.Range("D1"), order1:=xlAscending, _
Key2:=ws1.Range("E1"), order2:=xlAscending, Header:=xlYes
For i = 2 To LastRow
If ws1.Cells(i, "D").Value = "" Then
GoTo OverStepcode
ElseIf _
ws1.Cells(i, "D") = ws1.Cells(i + 1, "D") And _
(ws1.Cells(i, "E") < ws1.Cells(i + 1, "E") Or _
ws1.Cells(i, "E") = ws1.Cells(i + 1, "E")) Then
Rows(i).Delete
i = i - 1
End If
Next i
OverStepcode:
TimeElapsed = Round(Timer - StartTime)
MsgBox "The code ran successfully in " & TimeElapsed & " seconds vbinformation"
End Sub