2016-09-15 53 views
0

我正在嘗試創建一個按鈕,該按鈕將刪除一次點擊中應用於一個或多個列的過濾器。 但是,因爲我有一張受保護的牀單,我需要在此代碼中取消保護和保護牀單 此方法可行,但需要2秒,因爲我有4張受保護的牀單。 然後我得到了使用If條件的想法。使用VBA中的單個按鈕清除Excel中多個受保護工作表上的過濾器

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 sec..It旋轉不會刪除過濾器

有什麼錯在我的代碼?

+0

如果你刪除錯誤處理程序,VBA會給你一個調試嗎? [代碼評論](http://stackoverflow.com/questions/tagged/code-review)人們也可以幫助一些建議。 – Kevin

回答

0

假設沒有錯誤被OnError處理程序忽略,我的建議是用單獨的If語句替換ElseIf。我覺得那是一個陷阱。

相關問題