根据条件VBA删除表行

时间:2019-02-12 21:40:42

标签: excel vba excel-tables

我正在尝试基于两列中的值删除特定的表行。我试图将过滤器应用于表列以缩小标准,但是单击删除后,整个行将被删除,从而导致表外的值被删除。另外,宏录制器并不像我希望的那样动态,因为它仅选择录制时单击的单元格。

   Sub Macro2()
    '
    ' Macro2 Macro
    '
    '
         ActiveSheet.ListObjects("Table1").Range.AutoFilter Field:=1, Criteria1:= _
    "Apple"                               \\Narrowing criteria in Column 1 of the table
         Range("A4").Select               \\This only applies to a specific cell, and the value can shift
         Selection.EntireRow.Delete       \\This will delete the entire sheet row, I'd like for only the table row to be deleted    
         Range("A5").Select
         Selection.EntireRow.Delete
         Selection.EntireRow.Delete
    End Sub

enter image description here

是否存在一种方法,可以在满足条件的列中找到所需的字符串并仅删除表中的行?我试图仅删除ListObject.ListRows,但它仅引用我选择的行,而不引用基于条件的行。

2 个答案:

答案 0 :(得分:3)

您可以使用.DataBodyRange.SpecialCells(xlCellTypeVisible)将范围变量设置为等于过滤范围,然后取消过滤并删除:

Dim dRng As Range
With ActiveSheet.ListObjects("Table1")
    .Range.AutoFilter Field:=1, Criteria1:="Apple"
    If WorksheetFunction.Subtotal(2, .DataBodyRange) > 0 Then
        Set dRng = .DataBodyRange.SpecialCells(xlCellTypeVisible)
        .Range.AutoFilter
        dRng.Delete xlUp
    End If
End With

答案 1 :(得分:0)

您将必须指出要删除的单元格/范围。您可以使用find函数查找相关行。由于您的表是静态的,因此我建议使用以下宏。 for循环检查每一行也是可能的,但对于非常大的表而言效率不高。通过在c列中添加一个标志(例如,如果要删除则为1)来准备数据集会很有用。

泰特(Tate)的编辑建议看起来也很干净

Sub tabledelete()

Dim ws As Worksheet
Dim rangecheck As Range
Dim rcheck As Integer

Set ws = Sheets("Sheet1") 'fill in name of relevant sheet
Set rangecheck = Range("A1") ' dummy to get the do function started

Do While Not rangecheck Is Nothing
With ws
    With .Range("C2:C30") ' fill in relevant range of table
        Set rangecheck = .Find(what:=1, LookAt:=xlWhole)
    End With
If Not rangecheck Is Nothing Then 'only do something if a 1 is found
rcheck = rangecheck.Row
.Range(.Cells(rcheck, 1), .Cells(rcheck, 3)).Delete Shift:=xlUp 'delete 3 columns in row found
End If

End With

Loop

End Sub