Search code examples
excelvbamultiple-columnsdelete-row

Delete rows if partial string not found in variety of columns: VBA


I'm trying to create a macro that will delete rows that do not contain the partial string ".csv" in any of the cells in that row. That caveat is that the string will not appear in the same column(s).

The following code works if the ".csv" explicit is found in column B: (I need partial string search & across many columns)

    Sub DeleteRows()
' Defines variables
Dim Cell As Range, cRange As Range, LastRow As Long, x As Long


' Defines LastRow as the last row of data based on column E
LastRow = ActiveSheet.Cells(Rows.Count, "B").End(xlUp).row


' Sets check range as E1 to the last row of E
Set cRange = Range("B1:B" & LastRow)


' For each cell in the check range, working from the bottom upwards
For x = cRange.Cells.Count To 1 Step -1
    With cRange.Cells(x)
        ' If the cell does not contain one of the listed values then...
        If .Value <> ".csv" Then
        'And .Value <> "PENDING" And .Value <> "CANCELLED" Add to line above if you want to add specifications'
            ' Delete that row
            .EntireRow.Delete
        End If
    End With
' Check next cell, working upwards
Next x


End Sub

Solution

  • This adaptation of the posted code uses COUNTIF to search entire rows for any partial matches to .csv, if none are found the entire row is deleted.

    It can be adapted to only delete only part of the row if required but more information would be needed for that.

    Option Explicit
    
    Sub DeleteRows()
    ' Define variables
    Dim Cell As Range, cRange As Range, LastRow As Long, x As Long
    Dim Res As Variant
    
        ' Define LastRow as the last row of data based on column E
        LastRow = ActiveSheet.Cells(Rows.Count, "B").End(xlUp).Row
    
        ' Sets check range as E1 to the last row of E
        Set cRange = Range("B1:B" & LastRow)
    
        ' For each cell in the check range, working from the bottom upwards
        For x = cRange.Cells.Count To 1 Step -1
            ' find if '.csv' found in any cell in the row
            Res = Evaluate("COUNTIF(" & x & ":" & x & ", ""*.csv*"")")
            
            ' if '.csv' not found delete row
            If Res = 0 Then
                ActiveSheet.Rows(x).Delete
            End If
            
        Next x
    
    End Sub