I often receive Excel worksheets (with empty rows) which I have to process as a pivot table. Because pivot tables don't allow empty rows, I've made this script. Any feedback is welcomed.
' Removes empty rows from an sheet.
Public Sub RemoveEmptyLines()
Dim lastRow As Long
Dim currentRow As Long
Dim emptyLine As Boolean
Dim answer As Integer
Dim countDeleted As Integer
Application.ScreenUpdating = False
answer = MsgBox("Empty lines will be deleted." & vbLf & _
"Do you wish to continue?", _
vbYesNo, "Changing table-structure?")
If answer = vbYes Then
' Minus 1 => The last one we check will be the last
' but one row.
lastRow = Range("A1").SpecialCells(xlCellTypeLastCell).row - 1
currentRow = 1
countDeleted = 0
' Go until the last but two row! The last row can't
' be empty (Result of SpecialCells). So we don't have
' to check that.
While currentRow < lastRow
emptyLine = True
Do
' When the complete row is empty then delete it.
' Table structure might be changed while iterating
' through the inner loop. So repeat the check from
' the main loop.
If _
WorksheetFunction.CountA(Rows(currentRow + 1).EntireRow) = 0 _
And _
currentRow < lastRow _
Then
Rows(currentRow + 1).EntireRow.Delete
countDeleted = countDeleted + 1
lastRow = lastRow - 1
Else
' I case of "not empty" leave the inner loop and
' check the next line.
emptyLine = False
End If
Loop Until emptyLine = False
currentRow = currentRow + 1
Wend
MsgBox countDeleted & " rows have been deleted.", _
vbInformation, "Result"
End If
Application.ScreenUpdating = True
End Sub