' copy this into the Worksheet code module
Private Sub CommandButton1_Click() 'ActiveX button's click event handler
Const TABLE_NAME = "TableN" ' replace with your table name
Dim lo As ListObject
On Error Resume Next
Set lo = Me.ListObjects(TABLE_NAME)
If Err.Number <> 0 Then
MsgBox TABLE_NAME & " was not found. Check the table name", vbCritical + vbOKOnly, "Sub CommandButton1_Click()"
Exit Sub
End If
On Error GoTo 0
If Not lo.DataBodyRange Is Nothing Then lo.DataBodyRange.Delete
End Sub
Edit2 (multiple table cleanup)
' copy this into the Worksheet code module
Private Sub CommandButton1_Click() 'ActiveX button's click event handler
Dim lo As ListObject, TABLE_NAME
' Attention! tables on the same worksheet must not have the same rows/columns,
' otherwise you will get an error `Run-time error '1004': This operation is not allowed.
' The operation is attempting to shift cells in a table on your worksheet` or something like that.
For Each TABLE_NAME In Array("Table1", "Table2", "Table3") 'and so on
On Error Resume Next
Set lo = Me.ListObjects(TABLE_NAME)
If Err.Number <> 0 Then
MsgBox TABLE_NAME & " was not found. Check the table name", vbCritical + vbOKOnly, "Sub CommandButton1_Click()"
Exit Sub
End If
On Error GoTo 0
If Not lo.DataBodyRange Is Nothing Then lo.DataBodyRange.Delete
Next
End Sub
Edit3 (tables on the different sheets)
' copy this into the Worksheet code module
Private Sub CommandButton1_Click() 'ActiveX button's click event handler
Dim lo As ListObject, TABLE_NAME, arr
For Each TABLE_NAME In Array("Sheet1|Table1", "Sheet2|Table2") 'and so on
On Error Resume Next
arr = Split(TABLE_NAME, "|")
Set lo = Me.Parent.Sheets(arr(0)).ListObjects(arr(1))
If Err.Number <> 0 Then
MsgBox TABLE_NAME & " was not found. Check the table name", vbCritical + vbOKOnly, "Sub CommandButton1_Click()"
Exit Sub
End If
On Error GoTo 0
If Not lo.DataBodyRange Is Nothing Then lo.DataBodyRange.Delete
Next
End Sub
Attention! tables on the same worksheet must not have the same rows/columns, otherwise you will get an error Run-time error '1004': This operation is not allowed. The operation is attempting to shift cells in a table on your worksheet
or something like that.
An example of an acceptable table layout
