Search code examples
google-sheetsgoogle-sheets-apigoogle-sheets-macros

Google Sheets Macro: to auto sort on specific sheet and on multiple ranges


I'm trying to auto-sort 2 ranges on a specific googlesheet, however, I can only get it to work for one range (the last one identified in the code always works).

Would anyone know how to amend the code so it applies to both ranges (not just the last one)?

Thank you so much!

I have tried to duplicate the whole code for each and to combine the ranges ("b16:b55","b59:b100") but nothing worked.

function onEdit(){


var sh0 = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
var editedCell = sh0.getActiveRange().getColumnIndex();

if(editedCell == 1) { 
var range = sh0.getRange("b59:h100");
var range = sh0.getRange("b16:h55");

range.sort({column: 2});
}
}

this code would always sort by value in second column for range b16-b55. However, I want it to apply to that range AND b59:b100


Solution

  • If I understand you correctly, you'd like to sort both ranges by their value in column two.

    In your script, you currently reassign range right away and that's why B59:H100 won't ever be sorted.

    If you use two different variables you can then sort them individually by their respective values in column 2.

    var range1 = sh0.getRange("b59:h100");
    var range2 = sh0.getRange("b16:h55");
    
    range1.sort({column: 2});
    range2.sort({column: 2});