Running a system that is triggered by a control box. The code unprotects nearly all the sheets in the program using the following code (no problems):
Sub UnprotectSheets()
Dim wks As Worksheet
For Each wks In Worksheets
If wks.Name Like "Source Data Table" Or wks.Name Like "Permit Route Dashboard" _
Or wks.Name Like "Administrative Tasks" Or wks.Name Like "RP Calculation" Then GoTo Nextwks
wks.Unprotect Password:="Password"
Nextwks:
Next
End Sub
The program then conducts an analysis. At the end, I want to protect the same sheets, using the following code
Sub ProtectSheets()
Dim wks As Worksheet
For Each wks In Worksheets
If wks.Name Like "Source Data Table" Or wks.Name Like "Permit Route Dashboard" _
Or wks.Name Like "Administrative Tasks" Or wks.Name Like "RP Calculation" Then GoTo Nextwks
wks.Protect Password:="Password"
Nextwks:
Next
End Sub
However - I keep receiving the following error every time:
Run-time error '1004' Method 'Protect' of object _Worksheet' failed
Any help is appreciated. Thank you
The problem is that you are trying to protect an already protected sheet. Thus, simply run this:
Option Explicit
Sub TestMe()
Dim wks As Worksheet
For Each wks In Worksheets
If wks.ProtectContents Then
Debug.Print wks.Name & " is protected!"
Else
Debug.Print wks.Name & " is not protected!"
End If
Next wks
End Sub
Then go to the immediate window ( Ctrl + G ) and take a look at the report written there. It should look like this:
Sheet1 is not protected!
Sheet2 is protected!
In general, try to avoid GoTo
in VBA (and in every programming language), unless it is for error-catching. People become mad when they see these.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.