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
To create a bound script in Google Docs, Sheets, or Slides, open a document in Docs, a spreadsheet in Sheets, or a presentation in Slides and click Extensions > Apps Script. To reopen the script in the future, do the same thing or open the script from the Apps Script dashboard.
Within a script project, you can have multiple script file. For example, if you have three different things that you want to automate in Google Sheets and you create three different scripts for it, you can have all the three different scripts in the same Project file.
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.
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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With