0

我正在尝试根据两列中的值删除特定的表行。我试图将过滤器应用于表列以缩小我的条件,但是一旦我单击删除,整个行就会被删除,从而导致表外的值被删除。此外,宏记录器并不像我希望的那样动态,因为它只选择我在记录时单击的单元格。

   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

在此处输入图像描述

有没有办法在列中找到所需的字符串并在满足条件后仅删除表中的行?我试图只删除 ListObject.ListRows,但它只引用我选择的行,而不是基于条件的行。

4

2 回答 2

3

您可以使用.DataBodyRangeand.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
于 2019-02-12T22:22:24.607 回答
0

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

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

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
于 2019-02-12T22:41:53.647 回答