1
votes

in Google Sheets I have to repeat a function because getSheetByName() does not accept an array of sheets, it only accepts one sheet.

Is there a way to have one function that loops through specified sheets (not all sheets)?

i.e.
("Sheet1", "Sheet2" ) etc.

function recordHistory_1() {
        var ss = SpreadsheetApp.getActiveSpreadsheet();
        var sheet = ss.getSheetByName("Sheet1");
        var source = sheet.getRange("A2:B2");
        var values = source.getValues();
        values[0][0] = new Date();
        sheet.appendRow(values[0]);
};

function recordHistory_2() {
        var ss = SpreadsheetApp.getActiveSpreadsheet();
        var sheet = ss.getSheetByName("Sheet2");
        var source = sheet.getRange("A2:B2");
        var values = source.getValues();
        values[0][0] = new Date();
        sheet.appendRow(values[0]);
};

Reason I'm asking is because I have over 20 sheets, and so I have to write this function 20 times...

2

2 Answers

1
votes

You can also call the function once and loop through an array of sheetnames inside the function.

function recordHistory() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
["Sheet1", "Sheet2", "Sheet3"].forEach(function (s) {
    var sheet = ss.getSheetByName(s);
    var values = sheet.getRange('A2:B2').getValues()
    values[0][0] = new Date();
    sheet.appendRow(values[0]);
})
}
2
votes

You can generalize / reuse the same function for 20 different calls as follows.

    var sheetListArray = ["Sheet1", "Sheet2", "Sheet3"......"Sheet20"]
    var ss = SpreadsheetApp.getActiveSpreadsheet();

    for( var i = 1 ; i <= sheetListArray.length ; i++)
       // You can call the below function 20 time with different Sheet name each time.
      recordHistory(sheetListArray[i]);
    }

    function recordHistory(sheetName) {  
            var sheet = ss.getSheetByName(sheetName);
            var source = sheet.getRange("A2:B2");
            var values = source.getValues();
            values[0][0] = new Date();
            sheet.appendRow(values[0]);
    }