使用VBA中的单个按钮在Excel中的多个受保护工作表上清除过滤器

时间:2016-09-15 16:21:51

标签: excel-vba vba excel

我正在尝试创建一个按钮,只需单击即可删除应用于一列或多列的过滤器。 但是,由于我有受保护的工作表,我需要取消保护并保护代码中的工作表 这种方法有效,但由于我有4张受保护的纸张,所以需要大约2秒钟。 然后我有了使用If条件的想法。

Sub Resetauto()
On Error GoTo Handler

 Application.DisplayAlerts = False
 Application.ScreenUpdating = False

 If ActiveSheet.Name = "Sheet3" Then
 Sheets("Sheet3").Unprotect Password:="pass"
 ActiveWorkbook.ActiveSheet.ListObjects(1).Sort.SortFields _
    .Clear
 ActiveSheet.ShowAllData
 Sheets("Sheet3").Protect _
 Password:="pass", _
 UserInterfaceOnly:=True, _
 AllowFiltering:=True, _
 AllowSorting:=True, _
 AllowUsingPivotTables:=True

 ElseIf ActiveSheet.Name = "Sheet1" Then
 Sheets("Sheet1").Unprotect Password:="pass"
 ActiveWorkbook.ActiveSheet.ListObjects(1).Sort.SortFields _
    .Clear
 ActiveSheet.ShowAllData
Sheets("Sheet1").Protect _
Password:="pass", _
UserInterfaceOnly:=True, _
AllowFiltering:=True, _
AllowSorting:=True, _
AllowUsingPivotTables:=True

ElseIf ActiveSheet.Name = "Sheet4" Then
Sheets("Sheet4").Unprotect Password:="pass"
ActiveWorkbook.ActiveSheet.ListObjects(1).Sort.SortFields _
    .Clear
ActiveSheet.ShowAllData
Sheets("Sheet4").Protect _
Password:="Pass", _
UserInterfaceOnly:=True, _
AllowFiltering:=True, _
AllowSorting:=True, _
AllowUsingPivotTables:=True

Else
Sheets("Sheet5").Unprotect Password:="pass"
ActiveWorkbook.ActiveSheet.ListObjects(1).Sort.SortFields _
    .Clear
ActiveSheet.ShowAllData
Sheets("Sheet5").Protect _
Password:="pass", _
UserInterfaceOnly:=True, _
AllowFiltering:=True, _
AllowSorting:=True, _
AllowUsingPivotTables:=True
End If

Application.DisplayAlerts = True
Application.ScreenUpdating = True
Exit Sub

Handler:
Sheets("Sheet1").Protect _
Password:="pass", _
UserInterfaceOnly:=True, _
AllowFiltering:=True, _
AllowSorting:=True, _
AllowUsingPivotTables:=True

Sheets("Sheet2").Protect _
Password:="pass", _
UserInterfaceOnly:=True, _
AllowFiltering:=True, _
AllowSorting:=True, _
AllowUsingPivotTables:=True

Sheets("Sheet3").Protect _
Password:="pass", _
UserInterfaceOnly:=True, _
AllowFiltering:=True, _
AllowSorting:=True, _
AllowUsingPivotTables:=True

Sheets("Sheet5").Protect _
Password:="pass", _
UserInterfaceOnly:=True, _
AllowFiltering:=True, _
AllowSorting:=True, _
AllowUsingPivotTables:=True
Exit Sub
End Sub

此代码不执行任何操作,我的光标旋转2秒..它不会删除过滤器

我的代码中有什么问题吗?

1 个答案:

答案 0 :(得分:0)

假设OnError处理程序没有忽略任何错误,我的建议是用单独的If语句替换ElseIf。我发现那些是陷阱。