我正在尝试根据行H中单元格的值删除Excel工作表中的某些行。我正在尝试编写代码,以便它找到单词“deleted”或“processing”“random”。
现在我有一个代码可以查看整个工作表并根据一个值删除行,但有一种简单的方法可以对它进行编码以便它可以查找多个吗?
我目前的代码:
Dim r As Long, endRow As Long, pasteRowIndex As Long
endRow = 100 ' of course it's best to retrieve the last used row number via a function
For r = 1 To endRow 'Loop through Open Orders and search for my criteria
If Cells(r, Columns("H").Column).Value = "VARIABLE" Then 'Found
'Copy the current row
Rows(r).Select
Selection.Delete
End If
Next r
如果我只寻找一个值“变量”,这很有用,但我似乎无法弄清楚如何让它一次搜索多个。
答案 0 :(得分:0)
你可以试试这个:
Sub foo()
Dim r As Long, endRow As Long, pasteRowIndex As Long
endRow = 100 ' of course it's best to retrieve the last used row number via a function
For r = endRow To 1 Step -1 'Loop through Open Orders and search for my criteria
Select Case Cells(r, Columns("H").Column).Value
Case "deleted", "processing", "random"
Rows(r).Delete
Case Else
' Do nothing...
End Select
End If
Next r
End Sub
请注意,我颠倒了你的循环For r = endRow to 1 Step - 1
。从集合中删除项目时通常需要这样做,否则您必须重新编制索引,这会使代码更难以阅读。调试。
这是当前实施的区分大小写的匹配,因此它只查找所有小写。如果需要,我可以修改。
答案 1 :(得分:0)
问题在于,当您运行涉及删除整行的任何循环时,您必须使用Step -1
运行循环 BACKWARDS 。
Dim r As Long, endRow As Long, pasteRowIndex As Long, somevar as String
endRow = Range("H" & Rows.Count).End(xlUp).Row
For r = endRow to 1 Step -1
somevar = Range("H" & r).Value
If somevar = "VARIABLE" or somevar = "processing" or somevar = "Random" Then 'Found
Rows(r).Delete
End If
Next r