简体   繁体   中英

Delete empty cells (very slow)

I have a Range where I want to delete all empty cells. I developed the following solution but it is very very slowly. Could anyone help me to understand why this is so solw and what approach would lead to a faster solution.

Application.ScreenUpdating = False
    For i = letzte2 To 4 Step -1
        For j = 2 To 17
            If tab6.Cells(i, j) = "" Then
            tab6.Cells(i, j).Delete shift:=xlUp
            End If
        Next j
    Next i
Application.ScreenUpdating = True

Perform only one Delete :

Dim rDel As Range
Set rDel = Nothing
Application.ScreenUpdating = False
    For i = Letzte2 To 4 Step -1
        For j = 2 To 17
            If tab6.Cells(i, j) = "" Then
                If rDel Is Nothing Then
                    Set rDel = tab6.Cells(i, j)
                Else
                    Set rDel = Union(rDel, tab6.Cells(i, j))
                End If
            End If
        Next j
    Next i
If Not rDel Is Nothing Then
    rDel.Delete shift:=xlUp
End If
Application.ScreenUpdating = True

This can be done fairly easy (and effective) by using the SpecialCells() method. The following deletes all empty cells in a selection.

Sub DeleteEmptyCells()
    Dim Rng As Range

    Set Rng = Selection.SpecialCells(xlCellTypeBlanks)

    If Not Rng Is Nothing Then
        Rng.Delete shift:=xlUp
    End If
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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