What if last row doesn't have a value in Column A, but in a different column?
Anyway, I think this a a full solution, other then protecting against the sheet being protected.
It uses a lot of small functions to make it easier to understand. it doesn't rely on the COUNTA
or COUNT
functions.
LastRowInRange
will also work with subset ranges, instead of the entire sheet.
Sub ExampleCall()
Dim Sheet As Worksheet
' Clean up all sheets in ActiveWorkbook
For Each Sheet In ActiveWorkbook.Worksheets
DeleteEmptyRows Sheet
Next
End Sub
DeleteEmptyRows
Sub DeleteEmptyRows(Optional Sheet As Worksheet)
Dim LastRow As Long, Row As Long
Dim DeleteRange As Range
If Sheet Is Nothing Then Set Sheet = Application.ActiveSheet
LastRow = LastRowInRange(Sheet.UsedRange)
For Row = Sheet.UsedRange.Row To LastRow
If IsRowEmpty(Row, Sheet) Then Set DeleteRange = MakeUnion(DeleteRange, Sheet.Cells(Row, 1))
Next
If Not DeleteRange Is Nothing Then DeleteRange.EntireRow.Delete
End Sub
LastRowInRange
Public Function LastRowInRange(Target As Range) As Long
Dim Column As Range
Dim Row As Long, MaxRow As Long
If Target Is Nothing Then Exit Function
For Each Column In Target.Columns
' This check added, in case you want to look into a subset range and not an entire table/sheet.
If Column.Cells(Column.Row + Column.Rows.Count - 1) <> vbNullString Then
MaxRow = Column.Row + Column.Rows.Count - 1
Exit For
Else
Row = Column.Cells(Column.Row + Column.Rows.Count).End(xlUp).Row
If Row > MaxRow Then MaxRow = Row
End If
Next
LastRowInRange = MaxRow
End Function
IsRowEmpty
Public Function IsRowEmpty(Optional Row As Long = 1, Optional Sheet As Excel.Worksheet) As Boolean
Dim Col As Long
If Sheet Is Nothing Then Set Sheet = Application.ActiveSheet
Col = GetLastCol(Row, Sheet)
IsRowEmpty = (Col = 1) And (Trim(Sheet.Cells(Row, 1)) = vbNullString)
'For debuging, uncomment the following:
'If Sheet.Cells(Row, Col) <> vbNullString Then
' Debug.Print "Found something in Row " & Row & ", Col " & Col & ": """ & Sheet.Cells(Row, Col) & """"
'End If
End Function
GetLastCol
Public Function GetLastCol(Optional Row As Long = 1, Optional Sheet As Excel.Worksheet) As Long
If Sheet Is Nothing Then Set Sheet = Application.ActiveSheet
GetLastCol = Sheet.Cells(Row, Sheet.Columns.Count).End(xlToLeft).Column
End Function
MakeUnion
Public Function MakeUnion(Arg1 As Range, Arg2 As Range) As Range
If Arg1 Is Nothing Then
Set MakeUnion = Arg2
ElseIf Arg2 Is Nothing Then
Set MakeUnion = Arg1
Else
Set MakeUnion = Union(Arg1, Arg2)
End If
End Function