' 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(多表清理)
' 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(不同工作表上的表格)
' 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
注意力!同一个工作表上的表不能有相同的行/列,否则你会得到一个错误Run-time error '1004': This operation is not allowed. The operation is attempting to shift cells in a table on your worksheet
或类似的东西。
可接受的表格布局示例