My excel on default have all columns locked when I select protect sheet.
I’d like to use a VBA code where I only lock cells with formulas (and only allow users to select unlocked cells) while looping through every worksheet that I have in the workbook. This is the code that I currently have.
Sub LockSheets()
Dim ws As Worksheet
For Each ws In Worksheets
With ws
.Unprotect
.Cells.Locked = False
.Cells.SpecialCells(xlCellTypeFormulas).Locked = True
.Protect
End With
Next ws
End Sub
Is this what you are trying? I have commented the code so you should not have a problem understanding it. But if you do, then simply ask.
Option Explicit
'~~> Change this to the relevant password
Const myPass As String = "MyPassword"
Sub Sample()
Dim ws As Worksheet
Dim rng As Range
'~~> Loop through worksheets
For Each ws In ThisWorkbook.Sheets
With ws
Select Case .Name
'~~> Ignore these sheets
Case "Navigation", "Template", "Details"
Case Else
.Unprotect myPass
.Cells.Locked = False
'~~> Set your range which contains forulas
On Error Resume Next
Set rng = .Cells.SpecialCells(xlCellTypeFormulas)
On Error GoTo 0
'~~> If found then set them locked. This is required
'~~> because some sheet(s) may not have formulas
If Not rng Is Nothing Then rng.Locked = True
'~~> Reset to nothing to prevent false results
Set rng = Nothing
'~~> Protect sheet
.Protect myPass
'~~> Allow selectiong of only unlocked cells
.EnableSelection = xlUnlockedCells
End Select
End With
Next ws
End Sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With