Home » excel » excel – If any cells in column B contains string X, delete row and shift cells up

excel – If any cells in column B contains string X, delete row and shift cells up

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am not very experiences in excel, and not sure if this possible, but I am working with a very large excel spreadsheet and some of the cells in column B include values such as N/A.

I was wondering if there is a way to create some conditional statement that will delete all rows, if the cell in column B of that row includes N/A, and shift cells up after deleting?

I truly appreciate any advice as this will save me a great deal of time.

Many thanks in advance!

How to&Answers:

IF these are #N/A (system) errors, then using GoTo Special (Constants, Errors) makes this straight-forward:

Sub DeleteErrorRows()
    On Error Resume Next    'in case there are no errors in cells
    Range("B:B").SpecialCells(xlCellTypeConstants, 16).EntireRow.Delete
    On Error GoTo 0     'resume error handling
End Sub

I suspect it may be possible to use Replace to replace ‘N/A’ with ‘#N/A’ then use my procedure, although I haven’t tested this. Added Yes, it should work:

Sub DeleteErrorRows()
    Range("B:B").Replace "N/A", "#N/A"
    On Error Resume Next    'in case there are no errors in cells
    Range("B:B").SpecialCells(xlCellTypeConstants, 16).EntireRow.Delete
    On Error GoTo 0     'resume error handling
End Sub

Actually, I think this could be more generally applied, replacing some cell values with ‘#N/A’ as a mechanism for deleting rows 🙂

Answer:

Work from bottom-up, checking the values in column B for N/A, if found, you can use:

ActiveSheet.Cells(currentRow,1).EntireRow.Delete