Home » excel » vba – Deleting rows having a specific value in a specific column

vba – Deleting rows having a specific value in a specific column

Posted by: admin April 23, 2020 Leave a comment

Questions:
Sub main()
   Dim count As Integer
   Dim i As Integer
   count = Range("Q" & Rows.count).End(xlUp).Row
   MsgBox count
   For i = 2 To count
      If Cells(i, "Q").Value = 2 Then
           Sheets(1).Rows(i).EntireRow.Delete
      End If
  Next i
End Sub

Why the code is not working in the right away? When I execute the above VBA code in excel, it’s deleting some rows and then exiting out with this message:

run time error 13 

What does that mean? Sometimes I get this message:

type mismatch

In the above VBA code, I want to delete the rows whose Q column value is 2 but it’s not working. Could you please let me know where the bug is?

Let me tell you what’s happening. The code is working but it’s deleting some rows and aborting with run time error 13. When I opened my EXCEL file to see the Q column, what I observed is that some of the rows of Q column had #REF!.

I think this might be the cause but how do I make over it? How do I make my code to work right? I have a Q column consisting of 1,2 values in it. The row of Q column which has 2 in it must be deleted, I mean the entire row.

How to&Answers:

Looping through each row can be time consuming over a large worksheet. Try using the find method. Also turn off screenupdating.

Sub HTH()
    Dim rCell As Range
    Dim strAddress As String

    Application.ScreenUpdating = False

    With ActiveSheet.Columns("Q")
        Set rCell = .Find(What:=2, LookIn:=xlValues, SearchOrder:=xlByColumns)

        If Not rCell Is Nothing Then
            Do
                strAddress = rCell.Address
                rCell.EntireRow.Delete
                Set rCell = .FindNext(Range(strAddress))
            Loop Until rCell Is Nothing
        End If

    End With

    Application.ScreenUpdating = True

End Sub

Answer:

If row #10 == 2 then you delete row #10; on the next iteration of the loop you examine row #11 which now has the value of row #12 as it shifted-up after the delete, this means you skip looking at any row immediately under a deleted row.

You probably want to loop backwards;

Sub main()
   Dim count As Integer
   Dim i As Integer
   '//assuming all filled rows from Q2 downwards?
   count = Range("Q2").End(xlDown).Row

   For i = count To 2 Step -1
      If Cells(i, "Q").Value = 2 Then
           Sheets(1).Rows(i).EntireRow.Delete
      End If
  Next i
End Sub