如果列H包含以下任何值 - VBA,则删除行

CC2*_*268 -6 excel vba excel-vba

如果列H包含以下任何值,我想删除一行:

1) %
2) Resistor
3) Capacitor
4) MCKT
5) Connector
6) anything else I may want to add to this list...
Run Code Online (Sandbox Code Playgroud)

在谷歌上发现并编辑 - 它运作良好 - 不确定是否有更"有效"的方法来做到这一点.

Sub DeleteRows()
lastrow = Cells.SpecialCells(xlCellTypeLastCell).Row
readrow = 1
For n = 1 to lastrow
  If Range("H" & ReadRow).Value = "%" Or _
    Range("H" & ReadRow).Value = "Resistor" Or _
    Range("H" & ReadRow).Value = "Capacitor" Or _
    Range("H" & ReadRow).Value = "MCKT" Or _
    Range("H" & ReadRow).Value = "Connector" Then
    Range("H" & ReadRow).EntireRow.Delete
    Else
      readrow = readrow + 1
    End If
  Next
End Sub
Run Code Online (Sandbox Code Playgroud)

Sco*_*ner 5

有更有效的方法,但有这个:

  1. 向后循环.
  2. 将ReadRow更改为n,有两个变量没有意义:

码:

Sub DeleteRows()
Dim Lastrow as long, n as long
lastrow = Cells.SpecialCells(xlCellTypeLastCell).Row

For n =  lastrow to 1 Step -1
  If Range("H" & n).Value = "%" Or _
    Range("H" & n).Value = "Resistor" Or _
    Range("H" & n).Value = "Capacitor" Or _
    Range("H" & n).Value = "MCKT" Or _
    Range("H" & n).Value = "Connector" Then
        Rows(n).Delete
  End If
Next
End Sub
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用 Select Case

Sub DeleteRows()
Dim Lastrow as long, n as long
lastrow = Cells.SpecialCells(xlCellTypeLastCell).Row

For n =  lastrow to 1 Step -1

  Select Case Range("H" & n).Value 
      Case "%","Resistor","Capacitor","MCKT","Connector"
        Rows(n).Delete
  End Select
Next
End Sub
Run Code Online (Sandbox Code Playgroud)

它使添加到列表更容易.