I have a lost property register in Google Sheets which has columns A:I. As items are found, users add the items to the sheet so over time the sheet will have a significant number of rows. This is a sample of my sheet:
I have several buttons in row 1 which have GAS behind each so that a user can sort a particular column.
Column H is populated with a conclusion date and I want a button with GAS to first sort column G, the "Expiry Date" ascending which will always be populated and secondly column H, the "Conclusion Date" so that the empty cells are at the top ie all items that have not yet been concluded at the top of the sheet. I have the following GAS but this sends all of the empty cells to the bottom.
//Sort Lost Property Register By Column H function SortLostPropertyRegisterByColumnH() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheetByName('Lost Property Register'); var range = sheet.getRange("A3:I"); range.sort({column: 7, ascending: true}); range.sort({column: 8, ascending: false}); }
Is there any way to do this?
I believe your goal as follows.
A3:I
after the sort was finished.For this, how about this answer?
In this answer, I would like to propose the following flow.
A3:I
.When your script is modified, it becomes as follows.
function SortLostPropertyRegisterByColumnH() {
// 1. Sort the Spreadsheet.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Lost Property Register');
var range = sheet.getRange("A3:I" + sheet.getLastRow()); // Modified
range.sort({column: 7, ascending: true});
range.sort({column: 8, ascending: false});
// I added below script.
// 2. Retrieve the values from the range `A3:I`.
// 3. The rows with the empty cell at the column "H" are put to the top of values.
SpreadsheetApp.flush();
const values = range.getValues().reduce((o, e, i, a) => {
o[e[7].toString() == "" ? "blanks": "values"].push(e);
if (i == a.length - 1) o.result = o.blanks.concat(o.values);
return o;
}, {blanks: [], values: []});
// 4. Put the processed values to the Spreadsheet.
range.setValues(values.result);
}
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.