1

I'm trying to have an auto sort function only impact one sheet in a workbook rather than all of them. I've done this in other projects and def messed this up along the way - any help is appreciated!!

Here's where I'm at:

SORT_SHEET_NAME = "Active Portfolio";
SORT_DATA_RANGE = "A2:043";
SORT_ORDER = [
{column: 11, ascending: true},
{column: 10, ascending: true},
{column: 1, ascending: true}
];

function onEdit(e){
  multiSortColumns();
}
function multiSortColumns(){
    var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var range = sheet.getRange(SORT_DATA_RANGE);
  range.sort(SORT_ORDER);
  ss.toast('Ya Done Good, Kid.');
}

It sorts correctly on that sheet, but I don't want all the sheets to sort.

1 Answer 1

0

Try this:

function onEdit(e) {  
  const sh = e.range.getSheet();
  if(sh.getName() == "Your sheet name") {
  sh.getRange("A2:O43").sort([{ column: 11, ascending: true }, { column: 10, ascending: true }, { column: 1, ascending: true }]);
  e.source.toast('complete');
  }
}

This one will only do it when you are on the page that you select

or you could do it this way:

function onEdit(e) {  
  consg sh = e.source.getSheetByName('Your sheet name');
  sh.getRange("A2:O43").sort([{ column: 11, ascending: true }, { column: 10, ascending: true }, { column: 1, ascending: true }]);
  e.source.toast('complete');
  }
}

The latter will do it on every edit of any page, but it will only sort the page you have chosen.

2
  • Hi there! I tried both of these, but get the error message: TypeError: Cannot read property 'range' of undefined onEdit @ Code.gs:2 OR Attempted to execute onEdit, but could not save. Commented Feb 2, 2022 at 1:18
  • You cannot run these as standard function you simple paste them into script editor and then add the sheet name where appropriate and then simple edit the sheet in the appropriate manner and the function will be triggered by the onedit trigger. The error that you are seeing is normally caused by users trying to run the function from the script editor without supplying the event object which is provided by the onedit trigger.
    – Cooper
    Commented Feb 2, 2022 at 2:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.