简体   繁体   中英

How to delete rows in Excel based on more criterias using VBA?

I need to delete some rows, which contain specific data, when there are 2 or more conditions.

I have code like this:

For i = Cells(Rows.Count, "A").End(xlUp).Row To 2 Step -1
    If Cells(i, "D") <> "xx" Or Cells(i, "D") <> "xxx" Then Cells(i, "A").EntireRow.Delete         
Next i

but at the end, it deletes everything besides 1st row.

Nevertheless the code is working perfectly, when I have there only one condition:

  For i = Cells(Rows.Count, "A").End(xlUp).Row To 2 Step -1
  If Cells(i, "D") <> "xx" Then Cells(i, "A").EntireRow.Delete

This deletes everything besides rows, which contains 'xx' in column D.

What is wrong and why when I put second condition and or, is not working in the way I wish?

You have a small flaw in your AND/OR logic:

Sub qwerty()
   For i = Cells(Rows.Count, "A").End(xlUp).Row To 2 Step -1
       If Cells(i, "D") = "xx" Or Cells(i, "D") = "xxx" Then
       Else
          Cells(i, "A").EntireRow.Delete
       End If
   Next i
End Sub

here your updated code, try it:

For i = Cells(Rows.Count, "A").End(xlUp).Row To 2 Step -1
    If Not (Lcase(Cells(i, "D")) = "xx" Or Lcase(Cells(i, "D")) = "xxx") Then Cells(i, "A").EntireRow.Delete         
Next i

Lcase has been added to remove case sensitivity due to "XX" = "xx" will return false , but Lcase("XX") = "xx" will return true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM