Search code examples
sortinggoogle-sheetsgoogle-apps-script

Sort entire sheet in descending order


I am trying to create a function which sorts the sheet DATA by column 4, in descending order,

function specialSort(){
  var sheet = SpreadsheetApp.getActive().getSheetByName('DATA');
  sheet.sort({ column: 4, ascending: false })
}

Other answers (e.g., here) seem to recommend this approach. But why does this code throw the error Exception: Cannot convert '[object Object]' to int? If I instead use simply sheet.sort(4), I get the result I want (sorting the whole sheet by column 4), except that it's in ascending order.

Note well: I want to (descending) sort the whole sheet by column 4, not just the column itself.


Solution

  • From your script, I thought that sort(sortSpecOb) is for Class Range. The arguments of sort(columnPosition, ascending) of Class Sheet are columnPosition(Integer), ascending(Boolean). I thought that this might be the reason for your current issue. In your script, how about the following modification?

    Modified script:

    function specialSort() {
      var sheet = SpreadsheetApp.getActive().getSheetByName('DATA');
      sheet.sort(4, false);
    }
    

    References: