Forum Discussion

TaurusGear13's avatar
TaurusGear13
Copper Contributor
Dec 26, 2025

Unprotect in Office Scripts

I am writing an office script that requires sorting on a sheet with the overall sheet protected and specific cells not protected. I need to be able to sort an unprotected range using an automation but the protection is restricting it even though I have "sort" allowed in the protection options. Is there a way to unprotect and then re-protect the sheet as part of the scripts? Including passwords?

 

 

function main(workbook: ExcelScript.Workbook) {

  let selectedSheet = workbook.getActiveWorksheet();

  // Clear auto filter on selectedSheet

  selectedSheet.getAutoFilter().clearCriteria();

  // Custom sort on range range C9:I6001 on selectedSheet

  selectedSheet.getRange("C9:I6001").getSort().apply([{key: 0, ascending: true}], false, true, ExcelScript.SortOrientation.rows);

  // Apply values filter on selectedSheet

  selectedSheet.getAutoFilter().apply(selectedSheet.getAutoFilter().getRange(), 6, { filterOn: ExcelScript.FilterOn.values, values: ["1"] });

 

}

 

 

 

1 Reply

  • SergeiBaklan's avatar
    SergeiBaklan
    Diamond Contributor

    You may use this ExcelScript.WorksheetProtection interface - Office Scripts | Microsoft Learn interface. Didn't use it before, tested right now on

    function main(workbook: ExcelScript.Workbook) {
    	const sheet = workbook.getActiveWorksheet();
    	
    	const protection: ExcelScript.WorksheetProtection = sheet.getProtection()
    	protection.pauseProtection()
    	
    	sheet.getRange("C7:I39")
    		.getSort()
    		.apply(
    				[{ key: 0, ascending: true }]
    				, false
    				, false
    				, ExcelScript.SortOrientation.rows
    		)
    	
    	protection.resumeProtection()
    }

    It works with me, but only with Excel for web, not in desktop version. Didn't check with password, but it shall work, please check documentaion.

Resources