Union Movil
Union Movil

Reputation: 71

How to run a script multiple times

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);    
}

how can i specify in the script, (or better idea to take a number from a cell in my sheet) how many times run it ...

For example, lets say I want to duplicate 10 times my template sheet, then run it 10 times

Any help please ?

Thanks !

Upvotes: 0

Views: 585

Answers (1)

Jescanellas
Jescanellas

Reputation: 2608

You might want to take a look at JavaScript for Loop:


The for loop has the following syntax:

for (statement 1; statement 2; statement 3) {
  // code block to be executed
}

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.


Example:

for (i = 0; i < 5; i++) {
  text += "The number is " + i + "<br>";
  Logger.log(text);
}

In your case, put the code you want to repeat 10 times inside the for and run it from 0 to 9 times, or 1 to 10, as you prefer (0 to 9 is better as arrays's indexes start at 0).

Upvotes: 1

Related Questions