首页 文章

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

提问于
浏览
3

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

我的表看起来像这样

enter image description here

我希望删除每一行,如果列“从设备”和“到设备”开始用G或C(或者,更具体地说,如果“from”和“to”列以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不是的单元格,则该行仍将被删除,我想保留该行 .

有什么建议 ?谢谢!

1 回答

  • 3

    您可以在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
    

    要将其应用于您的代码,您只想在以下位置查看单元格的内容是否以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
    

    这应该会显着简化这个过程 .

相关问题