While protecting sheet, I'd like to disable "Select Locked Cells"

58 views Asked by At

I'm using xlwings and I'd like to protect sheet with un-check the "Select Locked Cells". I've tried many trys, such as "AllowSelectingLockedCellls=False", "SelectingLockedCells=False", etc, and I received a meassage from Python console that "TypeError: _Worksheet.Protect() got an unexpected keyword argument 'AllowSelectingLockedcells'". Is there any way that I can protect sheet and disable "Select Locked Cells"?

import xlwings as xw

folder = "C:\\Python\\DF\\"
xls = "65982.xlsx"

book = xw.Book(folder + xls)
book.app.visible = True
sht = book.sheets["Sheet1"]

sht.api.Protect(DrawingObjects=False, Contents=True, Scenarios=True,
        UserInterfaceOnly=False, AllowFormattingCells=False, AllowFormattingColumns=False,
        AllowFormattingRows=False, AllowInsertingColumns=False, AllowInsertingRows=False,
        AllowInsertingHyperlinks=False, AllowDeletingColumns=False, AllowDeletingRows=False,
        AllowSorting=False, AllowFiltering=False, AllowUsingPivotTables=False)
book.save()
1

There are 1 answers

0
moken On

As @Siddharth Rout states in his comment these are controlled by EnableSelection.

In the following code I remove the locking on cell 'A1' then apply one of the 3 options for EnableSelection;

xlNoSelection means I cannot select any cell when protection is enabled.
xlNoRestrictions means I can select any cell I choose when protection is enabled.
xlUnlockedCells means I can only select cells that are unlocked when protection is enabled. I.e I can select 'A1' on the sheet but no other cell.

import xlwings as xw
from xlwings.constants import EnableSelection

excel_file = 'test.xlsx'
with xw.App(visible=True) as app:
    wb = xw.Book(excel_file)
    ws = wb.sheets['Sheet1']

    ws.range('A1').api.Locked = False

    """ 
       Enable one of the following to set the specified requirement 
    """
    ### Not able to select any cells ###
    ws.api.EnableSelection = EnableSelection.xlNoSelection
    ### Select any cell ###
    # ws.api.EnableSelection = EnableSelection.xlNoRestrictions
    ### Select unlocked cells only ###
    # ws.api.EnableSelection = EnableSelection.xlUnlockedCells

    ws.api.Protect(Password='test')

    wb.save()