Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I lock cells with formulas?

Tags:

excel

vba

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
like image 418
vvv-1234 Avatar asked Dec 07 '25 10:12

vvv-1234


1 Answers

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
like image 127
Siddharth Rout Avatar answered Dec 09 '25 01:12

Siddharth Rout