Google-sheets – Duplicate sheet but keep protected range with exact same user as only editor

google sheetsgoogle-apps-script

The following code duplicates a sheet based on a template, and copies over the protected range permissions from the template sheet to the new sheet.

However, the permission range is now there in the new sheet, but not with the same user.

The template sheet has only one user that can edit, but for the new sheet, while the same range is restricted, all users from the entire spreadsheet can edit the new sheet.

Does anyone happen to know if I can make it be just the exact same user as the template? And not like the user that initiates the script but only the same user as the template. Here's the code:

function newSheet() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("New Sheet Template");
  var protections = sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE);
  var dateI = Browser.inputBox('Enter Date: ','(DD/MM/YYYY)', Browser.Buttons.OK_CANCEL);
  var nameSheet= "Sheet - "+dateI
   if (dateI == "cancel" ) {
    }
    else {
      ss.insertSheet(nameSheet, {template: sheet});
      ss.getRange('B4').setValue(dateI);    
      for (var i = 0; i < protections.length; i++) {
        var sheet2 = ss.getSheetByName("Sheet - "+dateI);
        var p = protections[i];
        var rangeNotation = p.getRange().getA1Notation();
        var p2 = sheet2.getRange(rangeNotation).protect();
        p2.setDescription(p.getDescription());
        p2.setWarningOnly(p.isWarningOnly());
    }
    }
}

Best Answer

Try the below script

In Google Sheets how do I duplicate a sheet along with its permission

It works from the "owner" account ... not from "editor" account. I have tested and it is working