2017-09-28 25 views
1

我有數據並完成了一些過濾。現在我想刪除整行直到最後一個可見行。另外,在這種情況下,我不想包含我的標題(第5行)。我不知道我應該如何解決與下面的代碼:選擇過濾的數據並刪除以顯示最後一行,不包括標題

Dim row1 As Variant 
row1 = Rows(5).Offset(1, 0) 
lastrow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row 
Rows("row1:" & lastrow).SpecialCells(xlCellTypeVisible).EntireRow.Delete 
+1

替換'「ROW1:」'和'ROW1&「:「' –

回答

0

您需要添加一個錯誤處理程序,只要用SpecialCells工作。

Sub DeleteVisibleRows() 
    With ActiveSheet 
     On Error Resume Next 
     .Range("A5", .Range("A" & .Rows.Count).End(xlUp)).Offset(1).EntireRow _ 
     .SpecialCells(xlCellTypeVisible).Delete 
     On Error GoTo 0 
    End With 
End Sub 
+0

我可以理解爲什麼需要錯誤處理程序謝謝你的代碼順便說一句 –

+0

'SpecialCells'將拋出一個錯誤,如果它不」?!找到任何細胞。 –

0

請試試這個...

Dim lr As Long 
lr = Cells(Rows.Count, 1).End(xlUp).Row 
Range("A6:A" & lr).SpecialCells(xlCellTypeVisible).EntireRow.Delete 

試試這個,如果你只是想,如果你要刪除可見行在數據集上應用過濾器。

Dim lr As Long 
lr = Cells(Rows.Count, 1).End(xlUp).Row 
If ActiveSheet.FilterMode Then 
    On Error Resume Next 
    Range("A6:A" & lr).SpecialCells(xlCellTypeVisible).EntireRow.Delete 
End If 
0

請嘗試以下:

Sub test() 

    Dim lastrow As Long 
    Dim rng As Range 

    lastrow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row 

    Set rng = Rows("6:" & lastrow) 

    rng.Delete Shift:=xlUp 

    End Sub 
相關問題