Delete all data rows from an Excel table (apart from the first) Delete all data rows from an Excel table (apart from the first) vba vba

Delete all data rows from an Excel table (apart from the first)


This is how I clear the data:

Sub Macro3()    With Sheet1.ListObjects("Table1")        If Not .DataBodyRange Is Nothing Then            .DataBodyRange.Delete        End If    End WithEnd Sub


Your code can be narrowed down to

Sub DeleteTableRows(ByRef Table As ListObject)    On Error Resume Next    '~~> Clear Header Row `IF` it exists    Table.DataBodyRange.Rows(1).ClearContents    '~~> Delete all the other rows `IF `they exist    Table.DataBodyRange.Offset(1, 0).Resize(Table.DataBodyRange.Rows.Count - 1, _    Table.DataBodyRange.Columns.Count).Rows.Delete    On Error GoTo 0End Sub

Edit:

On a side note, I would add proper error handling if I need to intimate the user whether the first row or the other rows were deleted or not


I have 3 routines which work just fine, just select a cell in a table and run one of the subroutines

Sub ClearTable()If Not ActiveCell.ListObject Is Nothing Then    ActiveCell.ListObject.DataBodyRange.Rows.ClearContentsEnd IfEnd Sub

and Shrink Table to remove the databody range except from the headers and the first data row

Sub ShrinkTable()If Not ActiveCell.ListObject Is Nothing Then    ActiveCell.ListObject.DataBodyRange.DeleteEnd IfEnd Sub

and Delete Table to completely delete the table from the sheet

Sub DeleteTable()If Not ActiveCell.ListObject Is Nothing Then    ActiveCell.ListObject.DeleteEnd IfEnd Sub