1

If a row has the value INACTIVE in column D and #N/A in column H, I want to delete that row.

I tried to achive that with my code below, but no row actually gets deleted.

Dim ws3 As Worksheet
Dim r As Integer
Set ws3 = ThisWorkbook.Sheets("Sheet2")
With ws3
For r = Sheet2.UsedRange.Rows.Count To 2 Step -1
If Cells(r, "D").Value = "INACTIVE" And Cells(r, "H").Value = "#N/A" Then
Sheet2.Rows(r).EntireRow.Delete
End If
Next
End With
2
  • 1
    You can use AutoFilter to get your rows and then delete them Commented Oct 31, 2019 at 10:05
  • Your If is checking the value of cells in the ActiveSheet, not in Sheet2. Maybe it should be something like If Sheet2.Cells(r, "D").Value or If ws3.Cells(r, "D").Value because you are mixing things here. ws3 is Sheet2 or is it Sheets("Sheet2")? is Sheet2=Sheets("Sheet2") your code is totally confusing. Commented Oct 31, 2019 at 10:10

1 Answer 1

2

Several issues.

  • You don't properly qualify your range objects.
    • You (properly) use With ws3 but then never refer back to it
  • If the #N/A is an actual error value, and not a text string, your macro will fail with a type mismatch error.
  • If the first row of UsedRange is not row 1, then rows.count.row will not reflect the last row
  • r should be declared as Long, not Integer.
    • Integer is limited to 32768 and there could be many more rows in a worksheet.
    • VBA will convert Integer to Long internally anyway.
  • Also, as pointed out by @FoxfireAndBurnsAndBurns Sheets("Sheet2") may not be the same as Sheet2. You seem to be using them interchangeably in your code. Set ws3 to whichever one you really want. And examine vba HELP for CodeName to understand the difference.

The following modification of your code may work:

Option Explicit
Sub due()
  Dim ws3 As Worksheet
  Dim r As Long
  Dim lastRow As Long

Set ws3 = ThisWorkbook.Sheets("Sheet2")
With ws3
    lastRow = .Cells(.Rows.Count, "D").End(xlUp).Row
    For r = lastRow To 2 Step -1
        If .Cells(r, "D").Value = "INACTIVE" And .Cells(r, "H").Text = "#N/A" Then
            .Rows(r).EntireRow.Delete
        End If
    Next
End With

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

3 Comments

while using this code, I have got the erro as "invalid outside procedure" for option explicit
@shnaky You have a typo or something other than what I have posted in your module.
@shnaky Also note that the screen shot you showed in your duplicate question does not have ANY rows that contain INACTIVE

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.