I have a sheet protection function I use, it allows me to store the protection password in one location, rather than everywhere I need to protect/unprotect the sheet:
Option Explicit
Public Sub SheetProtect(Optional wksCurr As Variant)
On Error GoTo Proc_Error
'
' Apply worksheet protection. If a sheet is passed, protect only that sheet,
' else protect all sheets
'
Dim strPW As String
strPW = "mypass"
If IsMissing(wksCurr) Then
For Each wksCurr In ThisWorkbook.Worksheets
wksCurr.Protect (strPW)
Next wksCurr
Set wksCurr = Nothing
Else
If VarType(wksCurr) = vbObject Then
If TypeOf wksCurr Is Worksheet Then
wksCurr.Protect (strPW)
End If
End If
End If
Proc_Exit:
Exit Sub
Proc_Error:
Select Case Err
Case Else
MsgBox "Error " & CStr(Err) & ": " & Err.Description
Resume Proc_Exit
End Select
Exit Sub
End Sub
Public Function SheetUnprotect(Optional wksCurr As Variant) As Boolean
On Error GoTo Proc_Error
'
' Apply worksheet protection. If a sheet is passed, unprotect only that sheet,
' else unprotect all sheets
'
Dim strPW As String
strPW = "mypass"
If IsMissing(wksCurr) Then
For Each wksCurr In ThisWorkbook.Worksheets
wksCurr.Unprotect (strPW)
Next wksCurr
Set wksCurr = Nothing
Else
If VarType(wksCurr) = vbObject Then
If TypeOf wksCurr Is Worksheet Then
SheetUnprotect = wksCurr.ProtectContents
wksCurr.Unprotect (strPW)
End If
End If
End If
Proc_Exit:
Exit Function
Proc_Error:
Select Case Err
Case Else
MsgBox "Error " & CStr(Err) & ": " & Err.Description
Resume Proc_Exit
End Select
Exit Function
End Function
Put it in a new module, change the password to match yours, then change the routine:
For A = LBound(WSNames) To UBound(WSNames)
SheetUnprotect(worksheets(wsnames(A)))
Worksheets(WSNames(A)).Range("H8:O27,H30:O41,U30:U41").ClearContents
SheetProtect(worksheets(wsnames(A)))
Next
You can add parameters to the .Protect statement, check the help files. I had some spreadsheets I support that had 40-50 locations that protected/unprotected the worksheets, this function cut down on maintenance quite a bit. You can also pass worksheets identified with their codenames to it.
Bookmarks