如何将脚本仅应用于Google电子表格中的一张工作表 [英] How do I apply a script to only one sheet within a google spreadsheet
问题描述
我有一个Google电子表格,其中包含两个工作表,分别称为Robin和Lucy. 每当我向A列添加一些数据时,我就制作/找到/修改了一个脚本以对工作表上的数据进行排序
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 } );
}
}
该脚本的效果很好,但我只希望将其应用到第一张纸上,罗宾.第二张表中的数据Lucy不一样,所以一旦我着手解决这个问题,我将为该脚本创建一个用于不同范围的脚本.
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.
我认为我需要使用getSheetByName("Robin"),但似乎无法正常工作. 预先感谢
I think I need to use the getSheetByName("Robin") but I can't seem to get it to work. Thanks in advance
推荐答案
您可以将整个函数置于这样的条件下:
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 } );
}
}
}
或者您也可以返回条件为false的情况,如下所示
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.
这篇关于如何将脚本仅应用于Google电子表格中的一张工作表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!