Justine Chacko
Justine Chacko

Reputation: 23

Google app script run function for sheets one by one

I have a google script which starts like below,

function popForm() {
  var ss = SpreadsheetApp.getActive();
  var sheet = ss.getSheetByName('Sheet1');
  var numberRows = sheet.getDataRange().getNumRows();
....
....

I have more sheets like Sheet2, Sheet3, Sheet4 etc. I would like to run same popForm function for all these sheets. Can I do it in one go?

Upvotes: 1

Views: 72

Answers (2)

Marios
Marios

Reputation: 27348

Explanation:

  • Essentially, you need to iterate over all the sheets of your spreadsheet file. To accomplish that you can create a new function runForAllSheets that calls popForm(sheet) for every sheet using forEach().

  • If you will, you can define instead your own custom list of sheets that you would like to be passed in popForm(sheet):

    var sheets = ['Sheet2','Sheet3','Sheet4 '];
    

Solution:

You just need to execute only runForAllSheets():

function runForAllSheets() {
  var ss = SpreadsheetApp.getActive();
  var sheets = ss.getSheets(); // All sheets
  //var sheets = ['Sheet2','Sheet3','Sheet4 ']; // Chosen sheets
  sheets.forEach(sh=>{
   popForm(sh);
  })
}


function popForm(sheet) {
  var ss = SpreadsheetApp.getActive();
  var numberRows = sheet.getDataRange().getNumRows();
  // ....
}

Upvotes: 2

Amit Agarwal
Amit Agarwal

Reputation: 11268

This might work

function popForm() {
  var ss = SpreadsheetApp.getActive();
  var sheets = ss.getSheets()
  for (var s=0; s<sheets.length; s++) {
    var sheet = sheets[s];
    var numberRows = sheet.getDataRange().getNumRows();
    ....
  }
}

Upvotes: 3

Related Questions