excel - VBA删除行包含特定的确切单词

标签 excel vba vba7

如果 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
编辑 2
Sub 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/

相关文章:

java - 如何使用 Apache POI 从 Excel 获取货币代码?

vba - 使用单个列表项创建 LIST 验证

xml - 在 VBA 中解析 XML 响应数据

excel - 如何使用 VBA 从不同列上显示的包装文本中获取文本

excel - 在指定日期范围内将 Outlook 电子邮件从最旧到最新导入 Excel

vba - 仅用一个 'Enter' 激活用户窗体

excel - 如何在没有填充的情况下更改excel中单元格的值

excel - 我应该如何在 VBA Excel 中为相同的对象使用 1 个代码

python-3.x - API VBA 的 eBay 数字签名可以,但 Python 签名验证无法满足请求

java - 在 Java Web 应用程序中读取 Excel 文件时出现字符编码问题