Google-sheets – How to run script on multiple Google Sheet tabs

google sheetsgoogle-apps-script

Here's my code

function saveRange(){
  var ss=SpreadsheetApp.getActiveSpreadsheet();
  var sheet=ss.getSheetByName('Sample_tab_1');
  var range=sheet.getRange('A8:AE47').getValues();

  sheet.getRange(sheet.getLastRow()+1, 1, range.length, range[0].length).setValues(range);  
}

But let's say I want to run this on not just Sample_tab_1 but also 2, 3, 4, etc. (not all of the tabs in the entire sheet though, just the ones I specify.)

Best Answer

An easy way to do that would be to save the tabs that you want to run the script on in an array and then use a for loop to cycle through that array and run the code on each specified tab.

It would look something like this:

function saveRange(){
    var tabs = [
        'Sample_tab_1',
        'Sample_tab_2',
        'Sample_tab_3',
        'Sample_tab_4'
    ];

    var ss=SpreadsheetApp.getActiveSpreadsheet();
    for (var i = 0; i < tabs.length; i++) {
        var sheet=ss.getSheetByName(tabs[i]);
        var range=sheet.getRange('A8:AE47').getValues();

        sheet.getRange(sheet.getLastRow()+1, 1, range.length, range[0].length).setValues(range);
    }
  }