VBA帮助。 删除基于多个标准的行

我正在寻找一些VBA的帮助来清理工作表,删除不需要的数据行,并保持基于多个条件的数据行。

我希望能够保留列A中任何等于“小计:”的行和列C中包含数字的任何行,同时删除与该条件不匹配的所有其他行。

清理前

希望的结果请求

我写了一个应该能够完成工作的function。

所以你可以调用一个子函数,并传递你想testing的列号(1代表“A”),你想testing的值(“”代表空白),你想testing的工作表名称。 最后一个参数是一个布尔值,如果是true,它将删除匹配条件中的值,否则将删除其他任何内容。

  Function DeleteCol(iCol As Integer, strCriteria As String, strWSName As String, bPositive As Boolean) Dim iLastCol As Integer Dim wsUsed As Worksheet Set wsUsed = ThisWorkbook.Worksheets(strWSName) iLastRow = wsUsed.Cells(Rows.Count, iCol).End(xlUp).Row For i = iLastRow To 1 Step -1 With wsUsed.Cells(i, iCol) If bPositive Then If .Value = strCriteria Then .EntireRow.Delete Else If .Value <> strCriteria Then .EntireRow.Delete End If End With Next i End Function 

所以做上面你所要求的,你可以做:

 Sub Delete() Call DeleteCol(1, "Subtotal:", "CoolSheetName", False) Call DeleteCol(3, "", "CoolSheetName", True) End Sub 

你可能想尝试下面的(注释)代码:

 Option Explicit Sub main() With Worksheets("MySheetName") '<--| change "MySheetName" to your actual sheet name With Intersect(.UsedRange, .Columns("A:C")) .AutoFilter Field:=1, Criteria1:="<>Subtotal" '<--| filter column "A" cells not containing "Subtotal" If Application.WorksheetFunction.Subtotal(103, .Resize(, 1)) > 1 Then .Offset(1).Resize(.rows.Count - 1).SpecialCells(xlCellTypeVisible).EntireRow.Delete '<--| delete any filtered cell row .AutoFilter '<--| show all data back With .Offset(1, 2).Resize(.rows.Count - 1, 1) '<--| consider column "C" cell from header row (excluded) down DeleteRows .Cells, xlCellTypeConstants, xlTextValues '<--| delete any "constant text" cell row DeleteRows .Cells, xlCellTypeFormulas, xlTextValues '<--| delete any "formula text" cell row DeleteRows .Cells, xlCellTypeBlanks, xlTextValues '<--| delete any "blank" cell row End With End With End With End Sub Sub DeleteRows(rng As Range, cellType As XlCellType, cellsValue As XlSpecialCellsValue) Dim f As Range Set f = rng.SpecialCells(cellType, cellsValue) If Not f Is Nothing Then f.EntireRow.Delete End Sub