Lock Cells in Excel With Python by Color, Font or Value
Locking cells in Excel with Python means setting each cell’s protection attribute and then protecting the sheet, because locking does nothing until protection is switched on. With pywin32 driving Excel on Windows, a script can pick which cells to lock by fill colour, font, formula or value, then protect each sheet with a password.
Setup
The script drives the real Excel application through pywin32, so it needs Windows with Excel installed. I wrote it in a Jupyter notebook; the GitHub repository also has it as a plain Python file. Install pywin32 from a terminal:
pip install pywin32
Then import win32com.client for Excel and Path from pathlib, which is part of Python, for the file paths.
from pathlib import Path # standard python module
import win32com.client # pip install pywin32
File paths
The workbook sits next to the notebook or script. The line below uses the folder of the Python file when there is one and falls back to Path.cwd() in a notebook, where __file__ does not exist.
# get current dir (using cwd() is needed when using notebooks)
current_dir = Path(__file__).parent if "__file__" in locals() else Path.cwd()
current_dir
The file’s own folder is the safer choice in a script, because it does not depend on where you start the script from; my pathlib quickstart explains the difference. The locked copy gets _locked added to the file name, so the original stays untouched.
excel_file_path = current_dir / "EBIT_2022.xlsx"
excel_file_path
output_path = current_dir / f"{excel_file_path.stem}_locked{excel_file_path.suffix}"
output_path
Open the workbook
Start Excel and open the workbook. Visible = True lets you watch the script work; set it to False to run Excel in the background.
# launch Excel
xl = win32com.client.Dispatch("Excel.Application")
xl.Visible = True
The example workbook has a few yellow input fields that feed an EBIT waterfall chart. The goal is to lock every cell except those inputs.
# open workbook
wb = xl.Workbooks.Open(excel_file_path)

Fill color as a number
Excel stores a fill color as one integer, not as RGB. The helper converts an RGB tuple into that integer so the script can compare it with each cell’s color. To find a cell’s RGB values, open the fill color menu, choose More Colors and read the Custom tab.
def rgb_to_int(rgb):
color_int = rgb[0] + (rgb[1] * 256) + (rgb[2] * 256 * 256)
return color_int
lock_color = rgb_to_int((255, 255, 153)) # yellow color
lock_color
Lock and protect
Locking a cell does nothing until the sheet is protected. The loop visits every cell in each sheet’s used range, unlocks the cells that match a condition, locks the rest and then protects the sheet with a password. It unprotects each sheet first, so you can run it again.
worksheet_password = "pw"
for sh in wb.Sheets:
wb.Worksheets(sh.Name).Activate()
ws = xl.ActiveSheet
rowcount = ws.UsedRange.Rows.Count
colcount = ws.UsedRange.Columns.Count
ws.Unprotect(Password=worksheet_password)
for row in range(1, rowcount + 1):
for col in range(1, colcount + 1):
cell = ws.Cells(row, col)
if cell.Font.FontStyle == "Bold":
cell.Locked = False
# if cell.Value == "Input Fields":
# cell.Locked = False
# if not cell.HasFormula:
# cell.Locked = False
# if cell.Interior.Color == lock_color:
# cell.Locked = False
else:
cell.Locked = True
ws.Protect(Password=worksheet_password)
The active condition unlocks bold cells. After a run, only bold cells such as Input Fields or EBIT 2021 can be edited; typing anywhere else shows Excel’s protected-sheet warning.

Other conditions
Three more conditions are already in the loop as comments. To switch, comment out the active if and uncomment another one. The first unlocks only the cell whose value is “Input Fields”:
if cell.Value == "Input Fields":
cell.Locked = False
This one unlocks every cell without a formula, so only formula cells such as B11 stay locked:
if not cell.HasFormula:
cell.Locked = False
The last one unlocks every cell with the yellow fill from the helper function, which is the goal for this workbook:
if cell.Interior.Color == lock_color:
cell.Locked = False
Tip: write Interior.Color with a capital C. With some pywin32 setups (once Excel’s type library has been cached), the lowercase .color from the original notebook raises an AttributeError.
Save and check
Save the result under the new name, close the original without saving changes and quit Excel. SaveAs needs the path as a plain string, which is why it is wrapped in str().
# Save & close workbook
wb.SaveAs(Filename=str(output_path))
wb.Close(False)
# Quit Excel instance
xl.Quit()
xl = None
Open the new EBIT_2022_locked.xlsx: only the yellow input fields accept input.

To edit everything again, go to Review, click Unprotect Sheet and enter the password. Sheet protection keeps people from typing over cells by accident; it is not encryption and does not stop someone who wants to get around it.

If you only need to lock every formula and keep the input cells open, without code, I am building an add-in for that called LockPop. It is not in Microsoft Marketplace yet, so for now the Python route above is the way to do it. To do the opposite clean-up, see how to convert all Excel formulas into values with Python.
