I'm running this script on a Google Form responses sheet:
function autoSort(sheet) {
var SORT_COLUMN_INDEX = 10;
var ASCENDING = true;
var NUMBER_OF_HEADER_ROWS = 1;
var range = sheet.getDataRange();
if (NUMBER_OF_HEADER_ROWS > 0) {
range = range.offset(NUMBER_OF_HEADER_ROWS, 0);
}
range.sort( {
column: SORT_COLUMN_INDEX,
ascending: ASCENDING
} );
}
function onOpen(event) {
autoSort(event.source);
}
I set a trigger to run the script whenever the sheet is opened. The script is functioning properly, but I'm getting emails telling me it failed. In the Execution list the error reported is:
TypeError: sheet.getDataRange is not a function
at autoSort(Autosort:5:21)
I used the same script in another very similar form and I didn't have these errors. Can anyone illuminate me what is wrong? Why is a failure being reported while the script works as requested?
onOpen()
,event.source
is a reference to the Spreadsheet doc ref. Howeverautosort()
assumes it is a reference to the sheet. Consider defining the sheet name as a variable and usinggetSheetByName(name)
doc ref.var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet name");
before theautoSort(event.source);
line?autoSort(sheet)
elsewhere in the project. So, rather than usegetSheetByName()
(which would be a reasonable approach), I have posted an answer that uses the event object:source
plusgetActiveSheet()
to "define" the sheet.