根据条件VBA删除表行

问题描述 投票:0回答:2

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

   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,但它只引用我选择的行,而不是基于一个关闭标准。

excel vba excel-tables
2个回答
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

0
投票

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

Tate的EDIT建议看起来也很干净

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
© www.soinside.com 2019 - 2024. All rights reserved.