我有两列,其中包含某些组件的规范。 基本上,如果两个指定列的首字母与 S 不同,我想删除整行。
我的 table 看起来像这样
如果“从设备”和“到设备”列以 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/