如何在Excel中使用VBA删除包含多个文本字符串之一的行



我在Excel中使用VBA的知识/经验非常少,我正在尝试找到一种方法,如果行中的任何单元格包含多个文本字符串中的一个,则可以删除整行。经过一两次谷歌搜索,我发现了这个页面:

https://excel.officetuts.net/vba/delete-a-row-if-cell-contains/

建议使用以下代码:

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("delete"))
If pos > 0 Then
rng.Item(i).EntireRow.Delete
End If
Next i
End Sub

上面的例子将删除包含文本"0"的任何行;删除";并且不区分大小写。

我想实现的是类似的功能,但能够使用多个文本字符串,以便所有包含单词";删除";或";香蕉;或";医院";将被删除。有没有办法修改这个示例代码来实现我的目标,或者需要完全不同的方法?

提前感谢您的帮助。

Sub DeleteRows()
Dim rng As Range
Set rng = ActiveSheet.UsedRange
For i = rng.Cells.Count To 1 Step -1
If InStr(LCase(rng.Item(i).Value), LCase("delete")) <> 0 _
Or InStr(LCase(rng.Item(i).Value), LCase("banana")) <> 0 _
Or InStr(LCase(rng.Item(i).Value), LCase("hospital")) <> 0 _
Then
rng.Item(i).EntireRow.Delete
End If
Next i
End Sub

可以使用关键字ORAND将布尔表达式添加到一起。当找到子字符串时,Instr返回一个数字,当找不到子字符串时返回0。所以我们只需要确认instr返回";而不是0";。因此,如果其中一个返回";不是0";则表达式为CCD_ 4。

删除多条件行

Option Explicit
Sub DeleteCriticalRows()

Dim Criteria As Variant: Criteria = Array("delete", "banana", "hospital")

Dim rng As Range: Set rng = ActiveSheet.UsedRange ' Used Range

Dim rrg As Range ' Current Row Range
Dim rCell As Range ' Current Cell in Current Row Range
Dim r As Long ' Current Row

' Loop through the rows of the range from the bottom to the top.
For r = rng.Rows.Count To 1 Step -1 ' 'To 2' if headers
Set rrg = rng.Rows(r)
' Loop through each cell of the current row range (from left to right).
For Each rCell In rrg.Cells
If IsNumeric(Application.Match(CStr(rCell.Value), Criteria, 0)) Then
rrg.Delete
Exit For ' no need to loop cells in this row any more
End If
Next rCell
Next r
MsgBox "Critical rows deleted.", vbInformation
End Sub

最新更新