Excel VBA – dynamic过滤范围删除

我有以下代码块来取出各种错误,并为数据分配一个错误代码描述。 只要filter返回结果,它就可以正常工作。 如果没有,则删除标题行。 我怎样才能防止发生? 提前致谢。

Sheets("Tempsheet").Select Range("A1:K1").AutoFilter Range("A1:K1").AutoFilter Field:=5, Criteria1:="0", Criteria2:=0 Range("K2:K" & Range("A" & Rows.Count).End(xlUp).Row).Formula = "Excluded: $0.00 Amount" Range("A2:K" & Range("A" & Rows.Count).End(xlUp).Row).EntireRow.Copy Sheets("Excluded").Select Range("A2").PasteSpecial Sheets("Tempsheet").Select Range("A2:K" & Range("A" & Rows.Count).End(xlUp).Row).EntireRow.Delete Sheets("Tempsheet").AutoFilterMode = False 

如果filter没有返回数据,则Range("A2:K" & Range("A" & Rows.Count).End(xlUp).Row)将返回第1行,因此在执行Delete之前testingrow > 1

 If Range("A2:K" & Range("A" & Rows.Count).End(xlUp).Row).Row > 1 then ... .Delete End If 

像这样的testing过滤结果的代码应该这样做

 Dim ws As Worksheet Dim ws2 As Worksheet Set ws = Sheets("Tempsheet") Set ws2 = Sheets("Excluded") Set rng1 = ws.Range(ws.[a1], ws.Cells(Rows.Count, "k").End(xlUp)) rng1.AutoFilter Field:=5, Criteria1:="0", Criteria2:=0 If rng1.SpecialCells(xlVisible).Rows.Count > 1 Then ws.Range("K2:K" & Range("A" & Rows.Count).End(xlUp).Row).Formula = "Excluded: $0.00 Amount" ws.Range("A2:K" & Range("A" & Rows.Count).End(xlUp).Row).EntireRow.Copy ws2.[a2].PasteSpecial Paste:=xlPasteValues rng1.Offset(1, 0).Resize(rng1.SpecialCells(xlVisible).Rows.Count - 1).EntireRow.Delete End If Sheets("Tempsheet").AutoFilterMode = False 
 Sheets("Tempsheet").Select Range("A1:K1").AutoFilter Range("A1:K1").AutoFilter Field:=5, Criteria1:="0", Criteria2:=0 Range("K2:K" & Range("A" & Rows.Count).End(xlUp).Row).Formula = "Excluded: $0.00 Amount" Range("A2:K" & Range("A" & Rows.Count).End(xlUp).Row).EntireRow.Copy Sheets("Excluded").Select Range("A2").PasteSpecial Sheets("Tempsheet").Select if Range("A" & Rows.Count).End(xlUp).Row > 1 then Range("A2:K" & Range("A" & Rows.Count).End(xlUp).Row).EntireRow.Delete end if Sheets("Tempsheet").AutoFilterMode = False