如果 A 列包含“string1”,我想从 Excel 中删除行,如下表所示:
A1
B1
字符串 1 字符串 2
字符串 3 字符串 4
字符串 5 字符串 6
字符串 7 字符串 8
我正在使用以下代码:
Sub DeleteRows()
Dim rng As Range
Dim pos As Integer
Set rng = ActiveSheet.UsedRange
For i = rng.Cells.Count To 1 Step -1
pos = InStr(LCase(rng.Item(i).Value), LCase("string1"))
If pos > 0 Then
rng.Item(i).EntireRow.Delete
End If
Next i
End Sub
问题是,如果 A 列包含“string11”而不是“string1”,它也会删除该行。请问有什么建议吗?
谢谢
最佳答案
与 Split()
(经过测试;未优化):
Sub DeleteRows()
Dim rng As Range
Set rng = ActiveSheet.UsedRange
For i = rng.Cells.Count To 1 Step -1
For Each w In Split(LCase(rng(i).Value))
If w = "string1" Then
rng(i).EntireRow.Delete
Exit For
End If
Next
Next i
End Sub
编辑 2Sub DeleteRows()
Dim rng As Range, i As Long, w, arr
arr = Array("string1", "string2", "string3")
Set rng = ActiveSheet.UsedRange
For i = rng.Cells.Count To 1 Step -1
For Each w In Split(LCase(rng(i).Value))
If IsNumeric(Application.Match(w, arr, 0)) Then
rng(i).EntireRow.Delete
Exit For
End If
Next
Next i
End Sub
关于excel - VBA删除行包含特定的确切单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68667399/