Home > other >  Unprotect a range in a Protected Sheet
Unprotect a range in a Protected Sheet

Time:05-18

I have a protected worksheet with 7 range exceptions that are not protected. I'd like to remove protection from one more range (a cell) on the sheet, for a total of 8 unprotected ranges. I've read several examples in SO but so far none seem to work.

Here's my code

    var ss=SpreadsheetApp.openById('id'); // get sheet
    ss.getSheetByName('Sheet1').getRange(4,2,1,1).protect().remove(); //get and remove protection on cell
    ss.getSheetByName('Sheet1').getRange(5,2,1,1).setValue('Code ran'); //confirm code ran

As you can see, I'm running a line to confirm that the code is running, and it is. But the protection is not removed from cell range 4,2,1,1.

Obviously, I'm missing something.

Thanks.

CodePudding user response:

Try the following script:

function myfunction()
{
  var ss=SpreadsheetApp.openById('ID'); // get sheet
  var range = ss.getSheetByName('Sheet1').getRange(4,2,1,1); // gets the specific range you are trying to unprotect.
  ss.getSheetByName('Sheet1').protect().setUnprotectedRanges([range]); //adds the exception to the current protection.
  ss.getSheetByName('Sheet1').getRange(5,2,1,1).setValue('Code ran'); //confirm code ran
}

After running that, the exception should look like this:

enter image description here

In my case I protected from A1 to C12 for the test.

Reference:

  • Related