Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I apply a script to only one sheet within a google spreadsheet

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

like image 223
oohrogerplamer Avatar asked Feb 13 '13 06:02

oohrogerplamer


People also ask

How do I bind a script in Google Sheets?

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.

Can you have multiple scripts in Google Sheets?

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.


2 Answers

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.

like image 187
Serge insas Avatar answered Oct 22 '22 22:10

Serge insas


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.
}
like image 25
tehhowch Avatar answered Oct 22 '22 23:10

tehhowch