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

后端 未结 9 2152
执笔经年
执笔经年 2020-12-01 09:16

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 alr

9条回答
  •  悲&欢浪女
    2020-12-01 10:02

    This VBA Sub will delete all data rows (apart from the first, which it will just clear) -

    Sub DeleteTableRows(ByRef Table as ListObject)
    
            '** Work out the current number of rows in the table
            On Error Resume Next                    ' If there are no rows, then counting them will cause an error
            Dim Rows As Integer
            Rows = Table.DataBodyRange.Rows.Count   ' Cound the number of rows in the table
            If Err.Number <> 0 Then                 ' Check to see if there has been an error
                Rows = 0                            ' Set rows to 0, as the table is empty
                Err.Clear                           ' Clear the error
            End If
            On Error GoTo 0                         ' Reset the error handling
    
            '** Empty the table *'
            With Table
                If Rows > 0 Then ' Clear the first row
                    .DataBodyRange.Rows(1).ClearContents
                End If
                If Rows > 1 Then ' Delete all the other rows
                    .DataBodyRange.Offset(1, 0).Resize(.DataBodyRange.Rows.Count - 1, .DataBodyRange.Columns.Count).Rows.Delete
                End If
            End With
    
    End Sub
    

提交回复
热议问题