I have a sheet with formulas in certain cell ranges. This spreadsheet is shared with multiple editors with edit permissions, but to protect formulas I have locked these ranges to prevent editing. I have created a script that duplicates a template and renames the sheet so that the editor can calculate the amount of material to prepare based on a number of people. The code to duplicate the template is template is as follows:
var ui = SpreadsheetApp.getUi();var ss = SpreadsheetApp.getActiveSpreadsheet();var userTxt = '';//Select last sheetfunction onOpen() { var totalSheets = ss.getNumSheets(); var activateLast = ss.setActiveSheet(ss.getSheets()[totalSheets - 1]);}//function newSheetWhithName() { var result = ui.prompt('Information','Please, type a name', ui.ButtonSet.OK_CANCEL); // Answer. var button = result.getSelectedButton(); userTxt = result.getResponseText(); if (button == ui.Button.OK) { // "OK". if (userTxt === ''){ ui.alert('Alert', 'You must type a correct name.', ui.ButtonSet.OK); }else{ duplicateProtectedSheet(userTxt); } } else if (button == ui.Button.CANCEL) { // "Cancel". ui.alert('Cancel'); }}function duplicateProtectedSheet(sheetName) { var old = ss.getSheetByName(sheetName); //Sheet already exists if (old) { ui.alert('there is already a sheet with that name'); }else{ var template = ss.getSheetByName("Template"); var duplicate = template.copyTo(ss).setName(sheetName); var p = template.getProtections(SpreadsheetApp.ProtectionType.SHEET)[0]; var p2 = duplicate.protect(); p2.setDescription(p.getDescription()); p2.setWarningOnly(p.isWarningOnly()); if (!p.isWarningOnly()) { p2.removeEditors(p2.getEditors()); p2.addEditors(p.getEditors()); } var ranges = p.getUnprotectedRanges(); var newRanges = []; for (var i = 0; i < ranges.length; i++) { newRanges.push(duplicate.getRange(ranges[i].getA1Notation())); } p2.setUnprotectedRanges(newRanges); ss.setActiveSheet(duplicate); ui.alert('Created'); }}
When the editor executes the script it correctly performs the function, except for the permissions, throwing the following error:
Exception: You do not have permission to do this.