Reputation: 65
I have a google spreadsheet with two sheets called Robin and Lucy. I've made/found/mangled a script to sort the data on the sheet each time I add some data to column A
function onEdit(event){
var sheet = event.source.getActiveSheet();
var editedCell = sheet.getActiveCell();
var columnToSortBy = 1;
var tableRange = "a2:I30";
if(editedCell.getColumn() == columnToSortBy){
var range = sheet.getRange(tableRange);
range.sort( { column : columnToSortBy } );
}
}
This script works great, but I only want it it be applied on the first sheet, Robin. The data in the second sheet, Lucy, isn't the same so I'm going to create another script for a different range for that one, once I get my head around this problem.
I think I need to use the getSheetByName("Robin") but I can't seem to get it to work. Thanks in advance
Upvotes: 5
Views: 11874
Reputation: 9862
Forward the event object received by onEdit
to the specific function which handles events on the desired sheet.
function onEdit(event) {
var name = event.range.getSheet().getName();
switch (name) {
case "Robin":
updateRobin(event);
break;
case "Lucy":
updateLucy(event);
break;
}
}
function updateLucy(event) {
// Code designed to handle edits to the "Lucy" sheet.
}
function updateRobin(event) {
// Code designed to handle edits to the "Robin" sheet.
}
Upvotes: 2
Reputation: 1
I would also suggest replacing this line: var tableRange = "a2:I30"; with this: var tableRange = sheet.getDataRange();
As your range grows, the range returned by getDataRange() will adjust to accommodate it. No need to use hard-coded address, makes the code more flexible
FYI: I've found some useful examples here:
http://www.javascript-spreadsheet-programming.com
Upvotes: 0
Reputation: 46794
You can put your whole function in a condition like this :
function onEdit(event){
var sheet = event.source.getActiveSheet();
if(sheet.getName()=='Robin'){
var editedCell = sheet.getActiveCell();
var columnToSortBy = 1;
var tableRange = "a2:I30";
if(editedCell.getColumn() == columnToSortBy){
var range = sheet.getRange(tableRange);
range.sort( { column : columnToSortBy } );
}
}
}
or you could also return if the condition is false like below
...
var sheet = event.source.getActiveSheet();
if(sheet.getName()!='Robin'){return}
...
Both methods will work the same way.
Upvotes: 7