我试图根据一列中的值来删除行,我知道有几种方法可以做到这一点,但我想知道为什么这种方法最终也会删除标题行。我知道有几种方法可以做到这一点,但我想知道为什么这种方法最终会把标题行也删除。我是否需要指定一个不同的范围?
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
尝试使用下面的代码。唯一不同的是,我在删除过滤行之前,重新定义了范围。
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
把它从: Cells(1, "D")
改为: Cells(2, "D")
这样能达到你想要的效果吗? 在Excel VBA以及其他环境中,总是(row,column)。 更多信息请看下面的链接。
https:/www.informit.comarticlesarticle.aspx?p=2021718&seqNum=7