Error - Cannot read properties of null

2,030 views
Skip to first unread message

Jody M

unread,
Sep 6, 2023, 7:37:36 AM9/6/23
to Google Apps Script Community
Hi, 

I'm a total Google Apps Script beginner and I keep running into an error that I can't figure out how to fix.

So, I am trying to run this script:
/** @OnlyCurrentDoc */
function sortResponses() {
var sheet = SpreadsheetApp.getActive().getSheetByName("Form Responses 1");
sheet.sort(1, false);
}

 but it keeps coming up with the following error message:
TypeError: Cannot read properties of null (reading 'sort')

Any help is much appreciated. It's driving me crazy!

Jody

Tanaike

unread,
Sep 6, 2023, 11:26:43 PM9/6/23
to Google Apps Script Community
Although, unfortunately, I cannot know your actual situation, I guess that your error of "TypeError: Cannot read properties of null (reading 'sort')" might be due to that "SpreadsheetApp.getActive().getSheetByName("Form Responses 1")" returns null. So, how about confirming the sheet name again?
Message has been deleted

Joe Leung

unread,
Sep 7, 2023, 9:22:34 AM9/7/23
to Google Apps Script Community
.sort() won't work on a sheet object. You need to get the data from the sheet first. 

To get the data, you need to define the range and then get the values from the range. Like this: 
/** @OnlyCurrentDoc */
function sortResponses() {
const sheet = SpreadsheetApp.getActive().getSheetByName("Form Responses 1");
let data = sheet.getDataRange().getValues();
data.sort(1, false);
}

On Wednesday, September 6, 2023 at 11:32:41 PM UTC-4 Pedri Haryadi wrote:
Maybe you can try:
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 1");

Jody M

unread,
Sep 7, 2023, 10:17:36 AM9/7/23
to Google Apps Script Community
Thanks for your replies. Your responses helped and I have figured it out!

On Thursday, September 7, 2023 at 4:32:41 AM UTC+1 Pedri Haryadi wrote:
Maybe you can try:
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 1");

Pada Kamis, 07 September 2023 pukul 10.26.43 UTC+7 Tanaike menulis:
Reply all
Reply to author
Forward
0 new messages