I recently wanted to lock only specific cells using VBA, so I learned the method for locking and unlocking cells programmatically.
Solution: Using the Locked Property
In Excel VBA, you can control whether cells are locked (editing prohibited) or unlocked (editing allowed) by setting the Locked property of the cells or worksheet.
How to Unlock Cells
By default, all cells in a new Excel sheet are locked. To lock only specific cells, you usually need to unlock everything first.
To unlock all cells in the active sheet:
ActiveSheet.Cells.Locked = False
- ActiveSheet: The currently active worksheet.
- Cells: Targets all cells in the sheet.
- Locked = False: Unlocks the cells (makes them editable).
How to Lock Specific Cells
Next, to lock only a specific cell (for example, cell A1), write the following:
ActiveSheet.Range("A1").Locked = True
- Range(“A1”): Specifies the target cell.
- Locked = True: Sets the cell to locked (not editable).
With this configuration, only cell A1 is uneditable, while all other cells remain editable.
Important: Enabling the Protection
Note: Even if you set the Locked property to True, the lock will not be effective unless the worksheet itself is protected.
You must add the following line to activate the protection:
ActiveSheet.Protect
Summary
The process for locking and unlocking cells in VBA is as follows:
- Unlock the entire sheet:
ActiveSheet.Cells.Locked = False - Lock specific cells:
ActiveSheet.Range("Target").Locked = True - Enable the lock settings: Protect the sheet using
ActiveSheet.Protect
By combining these steps, you can freely control which cells are editable and which are locked.
