简体   繁体   中英

Google App Script - Google-Sheet rows are not sorting by timestamp as expected

I am using JavaScript to sort the rows in a Google Sheet by the timestamp column. However, the sorting does not work properly as the most latest timestamp does not show on the top as it should. My data format of the timestamp column in the google Sheet is set to Short Date (mm/dd/yyyy).

What is the issue?

function onEdit() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = sheet.getRange(3, 1, sheet.getLastRow() - 2, sheet.getLastColumn());
  range.sort({column: 1, ascending: false});
}

Output: (Note how the row with timestamp 9/3 should be on the top but it is not!)
在此处输入图片说明

因为您在getRange(3,..)调用中排除了 A2(语法:getRange(行,列,行数,列数)),所以 A2 被排除在排序之外。

var range = sheet.getRange(1 + 1/*Modified*/, 1, sheet.getLastRow() - 1/*Modified*/, sheet.getLastColumn());

Solution:

In this particular scenario, you can also take the full range and sort by that:

function onEdit() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = sheet.getDataRange().sort({column: 1, ascending: false});
}

Restrictions:

This method only works for ascending: false , otherwise it will sort the headers as well.

References:

getDataRange()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM