Search code examples
excelvbaexcel-2007

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


Just recently I've been trying to delete all data rows in a table, apart from the first (which needs to just be cleared)

Some of the tables being actioned could already have no rows, so I was running it to problems as using .DataBodyRange.Rows.Count on a table with no rows (just header and/or footer) causes errors.

I looked all over for a solution an could not find a whole one, so I hope my answer to this question will be useful to others in the future.


Solution

  • 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 0
    End 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