带有特殊单元格的自动筛选器也可以删除行,也可以删除标题行

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

我正在尝试根据列中的值删除行。我知道有几种方法可以做到这一点,但我想知道为什么该方法最终也会删除标题行。我需要指定其他范围吗?

Sub DeleteForeign()
    Dim LastRow As Long
    Dim Rng As Excel.Range
'
' Choose entire column
    With ActiveSheet
        LastRow = .Range("D" & .Rows.Count).End(xlUp).Row
' Changing the range from Cells(1, "D") to Cells(2, "D") keeps the header intact,
' but deletes the next row which should be left since it has the value, "US"
        Set Rng = .Range(Cells(1, "D"), Cells(LastRow, "D"))
    End With
' This construct avoids looping which would be time-consuming for long lists
' Looking for country code, "US", and to delete all others
    With Rng
        .AutoFilter Field:=1, Criteria1:="<>US", Operator:=xlFilterValues
        .SpecialCells(xlCellTypeVisible).EntireRow.Delete
    End With
End Sub
excel vba autofilter
2个回答
0
投票

将其从:Cells(1, "D")更改为:Cells(2, "D")

这是您想要的吗?在Excel VBA和其他环境中,始终为(行,列)。有关更多信息,请参见下面的链接。

https://www.informit.com/articles/article.aspx?p=2021718&seqNum=7


0
投票

尝试使用以下代码:唯一的区别是,在删除过滤的行之前,我要重新定义范围。

Sub Macro2()

    Dim LastRow As Long

    LastRow = Range("D" & Rows.Count).End(xlUp).Row
    ActiveSheet.Range(Cells(1, "D"), Cells(LastRow, "D")).AutoFilter Field:=1, Criteria1:="<>US", Operator:=xlFilterValues
    Range(Cells(2, "D"), Cells(LastRow, "D")).SpecialCells(xlCellTypeVisible).EntireRow.Delete
    ActiveSheet.ShowAllData  

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.