I've seen this question return quite a few results here, but I'm having trouble getting it to work for my use case. Basically, I have a simple script that I want to run on multiple sheets in my spreadsheet (not every sheet, just the ones I define). I've tried defining the sheets and running a for
loop, but it fails when calling the method getRange. Anyway, here's my original script that defines only one sheet, and this works as expected:
var sheetToSort = "Sheet1";
var columnToSortBy = 1;
var rangeToSort = "A2:AB";
function onEdit() {
var sheet = SpreadsheetApp.getActiveSheet();
var editedCell = sheet.getActiveCell();
if (editedCell.getColumn() == columnToSortBy && sheet.getName() == sheetToSort) {
sortFormResponsesSheet();
}
}
function sortFormResponsesSheet() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetToSort);
var range = sheet.getRange(rangeToSort);
range.sort( { column : columnToSortBy, ascending: false } );
}