Hi All!! Plse HELP!!
I need to avail various ranges on different sheets in an in Excel 2003 workbook for users to type in. However, I need the cells to be locked upon saving of workbook. How do I do it?
Thanks
Luma
Hi All!! Plse HELP!!
I need to avail various ranges on different sheets in an in Excel 2003 workbook for users to type in. However, I need the cells to be locked upon saving of workbook. How do I do it?
Thanks
Luma
— following up on 's pointer about Tools->Protection: Excel's Locked flag only matters when the worksheet is protected. Two practical VBA patterns that meet your goal are below. Both assume you mark the cells users should be able to fill by clearing Format Cells -> Protection -> Locked (so only those start as editable).
Option A — lock every non-empty unlocked cell when the workbook is saved (simple, no per-change tracking). Put this in the ThisWorkbook module:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim ws As Worksheet
Dim rng As Range, c As Range
Dim psw As String
psw = "" ' set a password here if desired
Application.ScreenUpdating = False
For Each ws In ThisWorkbook.Worksheets
On Error Resume Next
ws.Unprotect Password:=psw
Set rng = ws.UsedRange.SpecialCells(xlCellTypeConstants)
On Error GoTo 0
If Not rng Is Nothing Then
For Each c In rng.Cells
If Not c.Locked Then c.Locked = True
Next c
End If
ws.Protect Password:=psw
Next ws
Application.ScreenUpdating = True
End Sub Option B — track changed ranges as users edit and lock only those specific ranges on save (more precise). Add a standard module with a public collection, initialize it on open, add a small Worksheet_Change to each sheet you want tracked, and then process that list in Workbook_BeforeSave. This keeps locks limited to the actual edited cells rather than every non-empty cell.
Notes and cautions
.Locked. The examples above unprotect/protect automatically. Jump to Post— joshSCH 1,062Tools-protection gives you 'locking' options.. is this what you mean?
Tools-protection gives you 'locking' options.. is this what you mean?
Hi joshSCH,
No. What I mean is that I need a script/code than runs "on change" locking only the changed cells. In other words, the user should be able to complete certain ranges, and upon saving, the changed (completed) cells should be locked, preventing future editting.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.