Union Movil
Union Movil

Reputation: 71

google sheet apps script how duplicate tab with same permissions

im using this script to duplicate and rename a template sheet

function duplicate() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var lastTabName = ss.getSheets().pop().getSheetName();  // Modified
  var sheet = ss.getSheetByName('Temp').copyTo(ss);

  // Duplica Template
  sheet.setName(isNaN(lastTabName) ? 1 : Number(lastTabName) + 1);  // Modified
  sheet.getRange("G2").setValue(Number(lastTabName) + 1 );

  ss.setActiveSheet(sheet);    
}

In that template sheet I have cell H1 protected, that only im available to edit, but not all other editors of the spreadsheet, also range B10:C136 the same (im only allowed to edit)

How can I modify that script, so when I run it, the template duplicates with the same protections, and the same condition that im the only one to be able to edit those ranges?

Thanks !

Upvotes: 0

Views: 1411

Answers (1)

Sourabh Choraria
Sourabh Choraria

Reputation: 2331

Try this -

function duplicate() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var lastTabName = ss.getSheets().pop().getSheetName();  // Modified
  var templateSheet = ss.getSheetByName('Temp')
  var newSheet = templateSheet.copyTo(ss);
  var protections = templateSheet.getProtections(SpreadsheetApp.ProtectionType.RANGE);

  // Duplicate Template
  newSheet.setName(isNaN(lastTabName) ? 1 : Number(lastTabName) + 1);  // Modified
  newSheet.getRange("G2").setValue(Number(lastTabName) + 1 );

  for (var i = 0; i < protections.length; i++) {
    var protection = protections[i];
    var protectedRange = protection.getRange().getA1Notation();
    var newProtection = newSheet.getRange(protectedRange).protect();
  }

  ss.setActiveSheet(newSheet);  
}

Please feel free to explore more examples from this documentation here.

Upvotes: 1

Related Questions