My Question: I am trying to delete rows in a table in column AH
and Criteria is "Del" so any cell in column AH
, I want to delete entire row in that table.
I tried so many different codes and most take forever as I have 10000+ rows to delete. I found this code from a site, but I am getting an error subscript out of range Error9
from the If Intersect
line:
Private Sub deleteTableRowsBasedOnCriteria(tbl As ListObject, _
columnName As String, _
criteria As String)
Dim x As Long, lastrow As Long, lr As ListRow
lastrow = tbl.ListRows.Count
For x = lastrow To 1 Step -1
Set lr = tbl.ListRows(x)
If Intersect(lr.Range, tbl.ListColumns(columnName).Range).Value = criteria Then
'lr.Range.Select
lr.Delete
End If
Next x
End Sub
Then I called the sub as below:
Set tbl = ThisWorkbook.Worksheets("Sheet1").ListObjects("Table4")
Call deleteTableRowsBasedOnCriteria(tbl, "AH", "Del")
Any help would be great. Thank you.
I changed your code a little bit and added a button to execute the delete rows function. I use the buttons caption to display how many rows have been deleted so you know what is happening. The key is to call
DoEvents
so everything is refreshed and have the button caption changed while the rows are being deleted:You add a button
CommandButton1
and try this code:On large Datasets like this I prefer to use arrays instead of deleting rows. The concept is pretty simple you load your
Target
cell values into an array (Data) and then create a second empty array the same size (NewData). Next you loop through the Data and copy any rows of Data that you want to keep the next empty row in NewData. Finally you overwrite theTarget
cell values with the NewData, effectively deleting the rows that you didn't want to keep.I actually went a step further here by adding a
PreserveFormulas
parameter. IfPreserveFormulas = True
then the formulas are copied to the NewData, instead of just the values.Note: 59507 rows deleting every other row. I compare Array Delete Data Only, Array Delete Preserve Formulas, Union Method and Filter Method. Download Test Stub
Results
Test
Code
You should be able to just use
AutoFilter
instead of a loop. It is much faster.