0

I need to delete rows that have a certain value in a certain column. The number of rows is variable. I tried to do this with the following VBA code:

Sub DeleteRows()

   Dim i, LastRow As Integer
   LastRow = ActiveSheet.Cells(Sheets(1).Rows.Count, 1).End(xlUp).row

   For i = 2 to LastRow

      If Cells(i, 1).Value <> "certain value" Then

         Rows(i).Delete

      End If

   Next i

End Sub

LastRow does contain the correct value. When I run this code, nothing happens. I'm new in VBA, I hope someone can push me in the right direction. Thanks in advance.

1

1 Answer 1

2

try this

Sub DeleteRows()

   Dim i as long, LastRow As long
   with activesheet
   LastRow = .Cells(.Rows.Count, 1).End(xlUp).row

   For i =  LastRow to 2 step -1

      If .Cells(i, 1).Value <> "certain value" Then

         .Rows(i).Delete

      End If

   Next i
   End With
End Sub
Sign up to request clarification or add additional context in comments.

1 Comment

I missed this also, change the declaration line to Dim i as Long, LastRow As Long If not i will be variant and LastRow will overflow if the rows are large.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.