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

纵饮孤独 提交于 2021-01-27 07:14:16

问题


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


回答1:


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.




回答2:


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.
}



回答3:


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



来源:https://stackoverflow.com/questions/14848006/how-do-i-apply-a-script-to-only-one-sheet-within-a-google-spreadsheet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!