Home > Software design >  Google app script prompt to rename tab when duplicated
Google app script prompt to rename tab when duplicated

Time:08-06

I have a simple script that duplicates the current tab in a sheet and moves it to the left but what I'd like to also add is a line that will also prompt me to name/rename the new duplicated tab. Currently I have this

function TemplateDuplication()

    {
      SpreadsheetApp.getActiveSpreadsheet().duplicateActiveSheet();
      SpreadsheetApp.getActiveSpreadsheet().moveActiveSheet(1);
    }

so basically when the script runs it duplicates the tab, moves it to the left, and asks to be renamed. Is that doable?

CodePudding user response:

Using the Ui and PromptReponse classes you can show a dialog box requesting an input.

This modification will show a dialog box requesting a name and leaves the default value if non is entered:

function TemplateDuplication(){
  var ui = SpreadsheetApp.getUi();
  var newName = ui.prompt("Enter a new name for the new Sheet- Optional").getResponseText();
  var newTab = SpreadsheetApp.getActiveSpreadsheet().duplicateActiveSheet();
  SpreadsheetApp.getActiveSpreadsheet().moveActiveSheet(1);
  if(newName) newTab.setName(newName);

}

This version shows the dialog box until a new name is entered:

function TemplateDuplication(){
  do{
  var ui = SpreadsheetApp.getUi();
  var newName = ui.prompt("Enter a new name for the new Sheet- Required").getResponseText();}
  while(!newName);  
  SpreadsheetApp.getActiveSpreadsheet().duplicateActiveSheet().setName(newName);
  SpreadsheetApp.getActiveSpreadsheet().moveActiveSheet(1);

}
  • Related