简体   繁体   English

Excel Vba-动态筛选器范围删除

[英]Excel Vba - Dynamic Filter Range Delete

I have the following code block to take out various errors and assign an error code description to the data. 我具有以下代码块,以提取各种错误并为数据分配错误代码描述。 It works fine as long as the filter returns a result. 只要过滤器返回结果,它就可以正常工作。 If it does not then it deletes the header row. 如果没有,则删除标题行。 How can I prevent that from happening? 如何防止这种情况发生? Thanks in advance. 提前致谢。

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

If no data is returned by the filter then Range("A2:K" & Range("A" & Rows.Count).End(xlUp).Row) will return row 1, so test for row > 1 before doing the Delete 如果过滤器未返回任何数据,则Range("A2:K" & Range("A" & Rows.Count).End(xlUp).Row)将返回第1行,因此在执行Delete之前测试row > 1

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

Something like this code which tests for a filter result should do it 像这样的代码可以测试过滤器结果

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM