Take the 2-minute tour ×
Web Applications Stack Exchange is a question and answer site for power users of web applications. It's 100% free, no registration required.

I am working with a simple spreadsheet that has name/lastnames in it. I need for the spreadsheet to automatically sort the entry alphabetically by the last name (column B). I have used the following code:

function onEdit(event){


  var sheet = event.source.getActiveSheet();
  var editedCell = sheet.getActiveCell();

  var columnToSortBy = 1;
  var tableRange = "A2:B500";

  if(editedCell.getColumn() == columnToSortBy){ 

      var range = sheet.getRange(tableRange);
      range.sort( { column : columnToSortBy } );
  }
}

However, when I run it, I get the following message: Cannot read property "source" from undefined. (line 2)

Could someone please help me figure out what I am doing wrong?

http://i.stack.imgur.com/ctZjB.png http://i.stack.imgur.com/ZuBpT.png

share|improve this question
add comment

3 Answers 3

This piece of code works:

function onEdit(){
  var sh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var editedCell = sh.getActiveRange().getColumnIndex();

  if(editedCell == 2) { 
    var range = sh.getRange("A2:B10");
    range.sort({column: 2});
  }
}

One key difference is the .getColumnIndex. Without it you don't receive an integer !!

See example file I've created: sorting

share|improve this answer
add comment

Here's a generic script that will autosort based on the 1st column, and assumes a Header row.

To create a script:

In the menu, go to Tools -> Script Editor... In the empty code window, paste the following code, which will run automatically whenever a cell is edited:

 /**
 * Automatically sorts the 1st column (not the header row) Ascending.
 */
function onEdit(event){
  var sheet = event.source.getActiveSheet();
  var editedCell = sheet.getActiveCell();

  var columnToSortBy = 1;
  var tableRange = "A2:T99"; // What to sort.

  if(editedCell.getColumn() == columnToSortBy){   
    var range = sheet.getRange(tableRange);
    range.sort( { column : columnToSortBy, ascending: true } );
  }
}
share|improve this answer
add comment

I used this piece of code:

/**
 * Automatically sorts the 1st column (not the header row) Descending.
 */
function onEdit(){
  var sh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var editedCell = sh.getActiveRange().getColumnIndex();

  if(editedCell == 2) { 
    var range = sh.getRange("A2:B100");
    range.sort({column: 2, ascending: false });
  }
}

and it works!

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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