如果行的一个单元格以特定字符串开头,VBA Excel 删除该行

标签 vba excel

我有两列,其中包含某些组件的规范。 基本上,如果两个指定列的首字母与 S 不同,我想删除整行。

我的 table 看起来像这样

enter image description here

如果“从设备”和“到设备”列以 G 或 C 开头(或者,更具体地说,如果“从”和“到”列以 S 开头,则保留整个行)行),我的代码如下:

Sub FilterData2()

Dim rcount As Long

With Sheet3
    rcount = Range("B" & Rows.Count).End(xlUp).Row
    With Range("E1:E" & rcount)
        If Application.WorksheetFunction.CountIf(Columns(5), "C*") > 0 Then
            .AutoFilter field:=1, Criteria1:="C*"
            .Offset(1).Resize(.Rows.Count - 1, 1).EntireRow.Delete
            .AutoFilter
        End If
        If Application.WorksheetFunction.CountIf(Columns(5), "G*") > 0 Then
             .AutoFilter field:=1, Criteria1:="G*"
             .Offset(1).Resize(.Rows.Count - 1, 1).EntireRow.Delete
             .AutoFilter
        End If
       End With
   End With

End Sub

但是,这只适用于 E 列,这意味着如果 G 列包含以 S 开头的单元格,而 E 列不包含,则该行仍会被删除,而我想保留该行。

有什么建议吗?谢谢!

最佳答案

您可以在 VBA 中组合 if 语句。

使用 AND 修饰符:

If Application.WorksheetFunction.CountIf(Columns(5), "C*") > 0 AND Application.WorksheetFunction.CountIf(Columns(5), "G*") > 0 Then

同样,您可以使用 OR 修饰符:

If Application.WorksheetFunction.CountIf(Columns(5), "C*") > 0 OR Application.WorksheetFunction.CountIf(Columns(5), "G*") > 0 Then

要将其应用到您的代码中,您只想查看单元格的内容在 from 或 to 中是否以 S 开头:

Dim rcount As Long
Dim i As Integer
Dim strE, strG As String

With Sheets("Sheet3")
    rcount = .Range("B" & Rows.Count).End(xlUp).Row

    For i = rcount to 2 Step -1
        strE = Left(.Cells(i, "E").Value, 1)
        strG = Left(.Cells(i, "G").Value, 1)
        If strE = "S" Or strG = "S" Then
        Else
            .Rows(i).EntireRow.Delete
        End If
    Next i
End With

这应该会大大简化流程。

关于如果行的一个单元格以特定字符串开头,VBA Excel 删除该行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46160137/

相关文章:

excel - 创建数据透视表时动态选择所有数据

excel - 如何将多列excel表格转换为附有标题的单列

excel - 计算一个范围内数字的多个实例

excel - 如果路径不存在,则询问用户文件夹路径

excel - 如何在 Excel 单元格中迭代字符时提高性能

vba - VBA 中排序功能的内存分配

vba - 使用 VBA 将 Excel xlsm 文件上传到 php 脚本

Excel公式比较两个数组

vba - 如何在VBA中设置和获取JSESSIONID cookie?

vba - 运行时错误 91 : Object variable or With block variable not set