Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete rows in an Excel ListObject based on criteria using VBA?

Tags:

excel

vba

I have a table in Excel called tblFruits with 10 columns and I want to delete any rows where the Fruit column contains Apple. How can I do this?

like image 414
Shawn H Avatar asked Apr 11 '15 22:04

Shawn H


1 Answers

The following sub works:

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

The sub can be executed like this:

Dim tbl As ListObject
Set tbl = ThisWorkbook.Worksheets("Sheet1").ListObjects("tblFruits")
Call deleteTableRowsBasedOnCriteria(tbl, "Fruit", "Apple")
like image 194
Shawn H Avatar answered Sep 20 '22 13:09

Shawn H