user4535384
user4535384

Reputation: 27

How do I create multiple spreadsheets from data in active spreadsheet Google Apps Script?

I am trying to create multiple spreadsheets, each with the title of the contents in the first column of the active worksheet. It does not create any of the worksheets once I put it in a for loop, what am I doing wrong? Google Apps Scripts

function main() {
  var limit = SpreadsheetApp.getActiveSheet().getLastRow();

  for (var i = 2; i <= limit; i++) {

    function createDocument() {
      var sheetname = SpreadsheetApp.getActiveSheet().getRange(i, 1).getValue();
      var doc = SpreadsheetApp.create(sheetname);
    }

  }
}

Upvotes: 1

Views: 83

Answers (1)

Yuri Khristich
Yuri Khristich

Reputation: 14527

You made a function createDocument() but you never called the function. It should be like this:

function main() {
  var limit = SpreadsheetApp.getActiveSheet().getLastRow();

  // the loop
  for (var i = 2; i <= limit; i++) {
    createDocument(); // call the function inside the loop
  }
}

// the function
function createDocument() {
  var sheetname = SpreadsheetApp.getActiveSheet().getRange(i, 1).getValue();
  var doc = SpreadsheetApp.create(sheetname);
}

Alternatively it can be done this way:

function main() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var names = sheet.getRange('A2:A'+sheet.getLastRow()).getValues();
  for (name of names) SpreadsheetApp.create(name);
}

Upvotes: 1

Related Questions