我有一个包含 5 个工作表的宏文件,我想在同一个文件中添加一个 VBA 命令按钮,以便单击即可清除所有工作簿内容。有人知道如何在 excel 2010 上使用 VBA 来执行此操作吗?
答案1
清除工作簿中的所有工作表:
Sub ClearAll()
Set wbook = ActiveWorkbook
For Each sht In wbook.Worksheets
sht.Activate
sht.Cells.Select
Selection.ClearContents
Selection.ClearFormats ' edit: clear formats too
sht.Cells(1, 1).Select ' edit: select the first cell to cancel selection of the whole sheet
Next sht
End Sub
编辑1:查看来源
删除它们而不是清理它们:
Sub DeleteAll()
bAlerts = Application.DisplayAlerts
Application.DisplayAlerts = False
Set wbook = ActiveWorkbook
wbook.Sheets(1).Activate
For Each sht In wbook.Worksheets
If sht.Name = wbook.ActiveSheet.Name Then ' we don't delete the active sheet but just its conntet
sht.Cells.Select
Selection.ClearContents
Selection.ClearFormats
sht.Cells(1, 1).Select
Else
sht.Activate
ActiveWindow.SelectedSheets.delete
wbook.Sheets(1).Activate
End If
Next sht
wbook.ActiveSheet.Name = "Sheet1" ' we rename the last remaining sheet to the default name
Application.DisplayAlerts = bAlerts
End Sub
答案2
简单如下。将 Sheet1、Sheet2 更改为您的工作表的名称,并根据需要添加这 3 行。我假设您知道如何在 Excel 中链接创建按钮并链接到宏。
Sub ClearSheets()
Sheets("Sheet1").Select
Cells.Select
Selection.ClearContents
Sheets("Sheet2").Select
Cells.Select
Selection.ClearContents
End Sub