[VBA] How to Lock and Unlock Cells: Using the Locked Property

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:

  1. Unlock the entire sheet: ActiveSheet.Cells.Locked = False
  2. Lock specific cells: ActiveSheet.Range("Target").Locked = True
  3. 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.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次