簡體   English   中英

Excel Vba-動態篩選器范圍刪除

[英]Excel Vba - Dynamic Filter Range Delete

我具有以下代碼塊,以提取各種錯誤並為數據分配錯誤代碼描述。 只要過濾器返回結果,它就可以正常工作。 如果沒有,則刪除標題行。 如何防止這種情況發生? 提前致謝。

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

如果過濾器未返回任何數據,則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

像這樣的代碼可以測試過濾器結果

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