Home > Back-end >  Google App script Remove Editors From Protection
Google App script Remove Editors From Protection

Time:06-07

In Google Sheets I am trying to remove editors using script from all the protection except the sheet owner and for this I am using below code, but after running the code the entire protection is being removed, however in place of removing the protection I want to remove all the user from the protection except the sheet owner. Further, when the code is run only one protection is removed at a time I want to apply it for all the protection.

function remove(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var protection = sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE)[0];
if (protection && protection.canEdit()) {
protection.remove();
}}

Any help on above will be appreciated.

CodePudding user response:

The changes that you should do to make the code only allow the spreadsheet owner be able to edit a protected range were already included on the Tainake's answer to your previous question Google Sheet Remove Editors After First Edit

From the question:

Further, when the code is run only one protection is removed at a time I want to apply it for all the protection.

sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE) returns an array of objects. To remove all the the protections your code should have to iterate over all the elements of this array. One of many ways to do this is by using Array.prototype.forEach, i.e.

function remove() {
  var sheet = SpreadsheetApp.getActiveSheet(); 
  sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE)
    .forEach(protection => {
      if (protection && protection.canEdit()) {
        protection.remove();
      }
    });
}

Resources

  • Related