In case you manage your data as a database and want to delete certain rows from it and you can filter them out, there is a trick to speed up the deletion process. This is very fast, unlike a simple loop:
I am comparing times for different examples (with 4806 lines).
- Standard delete cycle: 2:25
- Deletion Range: 0:20
- Filter Removal: 0:01
Example : I have data in "Tabelle5" and you want to delete certain rows. Data starts at line 6. Each line in column 1 starting with "OLD #" must be deleted.
1) Here is the standard solution (the longest time):
Dim i As Integer, counter As Integer Dim strToRemove As String, strToRemoveRange As String strToRemove = "OLD#" strToRemoveRange = "" counter = 0 With Tabelle5 For i = .UsedRange.Rows.Count To 6 Step -1 If Mid(.Cells(i, 1).value, 1, 4) = strToRemove Then .Rows(i).Delete Shift:=xlUp End If Next i End With
2) Here is the range decision (average time):
Dim i As Integer, counter As Integer Dim strToRemove As String, strToRemoveRange As String strToRemove = "OLD#" strToRemoveRange = "" counter = 0 With Tabelle5 For i = .UsedRange.Rows.Count To 6 Step -1 If Mid(.Cells(i, 1).value, 1, 4) = strToRemove Then If strToRemoveRange = "" Then strToRemoveRange = CStr(i) & ":" & CStr(i) Else strToRemoveRange = strToRemoveRange & "," & CStr(i) & ":" & CStr(i) End If counter = counter + 1 End If If counter Mod 25 = 0 Then If counter > 0 Then .Range(strToRemoveRange).Delete Shift:=xlUp strToRemoveRange = "" counter = 0 End If End If Next i If Len(strToRemoveRange) > 0 Then '.Range(strToRemoveRange).Delete Shift:=xlUp End If End With
3) Filter solution (shortest time):
Dim i As Integer, counter As Integer Dim strToRemove As String, strToRemoveRange As String strToRemove = "OLD#" strToRemoveRange = "" counter = 0 With Tabelle5 For i = .UsedRange.Rows.Count To 6 Step -1 If Mid(.Cells(i, 1).value, 1, 4) = strToRemove Then .Cells(i, 1).Interior.Color = RGB(0, 255, 0) counter = counter + 1 End If Next i If counter > 0 Then .Rows("5:5").AutoFilter .AutoFilter.Sort.SortFields.Clear .AutoFilter.Sort.SortFields.Add( _ Range("A5"), xlSortOnCellColor, xlAscending, , xlSortNormal).SortOnValue.Color = RGB(0, 255, 0) .AutoFilter.Sort.Header = xlYes .AutoFilter.Sort.MatchCase = False .AutoFilter.Sort.Orientation = xlTopToBottom .AutoFilter.Sort.SortMethod = xlPinYin .AutoFilter.Sort.Apply .Rows("6:" & CStr(counter + 5)).Delete Shift:=xlUp .Rows("5:5").AutoFilter End If End With
Here the green lines will be ordered from above, and the range of green strokes will be removed altogether. This is the fastest way I know! :-)
I hope this helps someone!
Regards Tom