2014-01-24 57 views
1

我有下面的代碼,它在列M下查找空單元。每找到一個空單元格,就會刪除整行。刪除不連續的整行時出錯

該代碼始終保留一行未刪除。

有人可以幫助確定代碼有什麼問題嗎?我懷疑在刪除一行時,單元格數量出錯了。

Private Sub CreateInvoice_Click() 

Dim LastRow As Long 
Dim cl As Range, rng As Range 

With Sheet4 
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row 

Set rng = Sheet4.Range("M1:M" & LastRow) 

For Each cl In rng 
If IsEmpty(cl) Then 
cl.EntireRow.Select ' MsgBox .Range("A" & cl.Row).Value & " has nothing in it" 
End If 
Next 

End With 

End Sub 

回答

1

,因爲它是刪除空行的最快和最有效的方式,我會用一個過濾器。下面也不使用.Select方法。

Sub RemoveEmpties() 
    Dim ws As Worksheet 
    Dim rng As Range 
    Dim lastRow As Long 

    Set ws = Sheet4 

    lastRow = ws.Range("M" & ws.Rows.Count).End(xlUp).Row 

    Set rng = ws.Range("M1:M" & lastRow) 

    With rng 
     .AutoFilter Field:=1, Criteria1:="" 
     .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete 
    End With 

    ws.AutoFilterMode = False 
End Sub 
+0

哇!奇妙的論壇!多謝你的快速回應。你的代碼做到了訣竅。花了2天試圖找到解決方案。 – newbi004

0
Columns("M:M").Select 

Selection.SpecialCells(xlCellTypeBlanks).Select  
Selection.EntireRow.Delete 

嘗試使用此

+1

感謝您的回覆。但是,我在選擇上遇到編譯錯誤。有什麼想法嗎? – newbi004

+0

** ThisWorkbook.Sheets(SheetName).Activate ActiveSheet.Columns(「M:M」)。Select Selection.SpecialCells(xlCellTypeBlanks).Select Selection.EntireRow.Delete ** –