Search code examples
google-apps-scriptgoogle-sheetsgoogle-sheets-apispreadsheet

Google Apps Script automatic (on edit) sort specific column (specific sheets only)


I am hoping that someone might be able to help me out, I've been doing a lot of searching in the past few days and coming up short of a solution. Likely has to do with my lack of knowledge on coding... I know enough to be dangerous, just not enough to be effective or efficient. Previously, I had Google Sheet data who consist of several sheet. Let's it named sheet 1 and sheet 2. For sheet 2, there are many columns (column 1 until 7) where at the column 1 and column 5, containing partially blank row.

To start, here is my goal.

  • To sort ascending my data from sheet 2 based column 3 and this sort only for sheet 2. Column 3 containing data date time.
  • If there is any edit or update data, always sort automatically

i had create this script before, but it is not worked. There is problem "TypeError: Cannot read properties of null (reading 'getSheetByName')"

 function AutoSortOnEdit() {
 var sheetNames = ["Sheet 2"];

  var ss = SpreadsheetApp.getActiveSpreadsheet();
    sheetNames.forEach(function(name) {
    var sheet = ss.getSheetByName(name);
  var range = sheet.getRange(2, 1, sheet.getLastRow() - 1, sheet.getLastColumn());
  range.sort({column: 3, ascending: true});
});

}


Solution

  • Try this:

    function onEdit(e) {
      const sh = e.range.getsheet();
      if (sh.getName() == "Sheet2") {
        sheet.getRange(2, 1, sheet.getLastRow() - 1, sheet.getLastColumn()).sort({ column: 3, ascending: true });
      }
    }