I have a Google Sheets file that has inside 2 Sheets. One is named "START" & the other "MASTER". 2sheets Start&Master The "START" sheet has a button that has an assigned script: Script Button The script duplicates the "MASTER" tab and renames it "DD/MM" which stands for Day/Month.
The script that is running is:
function duplicateSheetWithProtections() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
sheet = ss.getSheetByName('MASTER');
sheet2 = sheet.copyTo(ss).setName('DD/MM');
var protections = sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE);
for (var i = 0; i < protections.length; i++) {
var p = protections[i];
var rangeNotation = p.getRange().getA1Notation();
var p2 = sheet2.getRange(rangeNotation).protect();
p2.setDescription(p.getDescription());
p2.setWarningOnly(p.isWarningOnly());
if (!p.isWarningOnly()) {
p2.removeEditors(p2.getEditors());
p2.addEditors(p.getEditors()); // p2.setDomainEdit(p.canDomainEdit()); // only if using an Apps domain
}
}
}
I have 2 questions, how:
I believe your goal is as follows.
dd/MM
of today's date.If my understanding is correct, how about the following modification?
In your showing script, it seems that the text of DD/MM
is directly used as the sheet name. And, the created sheet is not moved.
function duplicateSheetWithProtections() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('MASTER');
var sheetName = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'dd/MM');
if (ss.getSheetByName(sheetName)) {
console.log(`Same sheet name of "${sheetName}" is existing. Please confirm the sheet name again.`);
return;
}
var sheet2 = sheet.copyTo(ss).setName(sheetName).activate();
var idx = ss.getSheets().findIndex(s => s.getSheetName() == "MASTER") + 2;
ss.moveActiveSheet(idx);
var protections = sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE);
for (var i = 0; i < protections.length; i++) {
var p = protections[i];
var rangeNotation = p.getRange().getA1Notation();
var p2 = sheet2.getRange(rangeNotation).protect();
p2.setDescription(p.getDescription());
p2.setWarningOnly(p.isWarningOnly());
if (!p.isWarningOnly()) {
p2.removeEditors(p2.getEditors());
p2.addEditors(p.getEditors());
// p2.setDomainEdit(p.canDomainEdit()); // only if using an Apps domain
}
}
}
When this script is run, a new sheet is inserted as the sheet name of the format dd/MM
of today's date. And, the new sheet is moved to just the right side of "MASTER" sheet.
In this modification, when the same sheet name exists in your Google Spreadsheet, a log with console.log(
Same sheet name of "${sheetName}" is existing. Please confirm the sheet name again.);
is shown, and the script is stopped. At that time, please remove or rename the existing sheet name.