仅在指定列更改时激活脚本

时间:2015-04-30 04:17:12

标签: javascript google-sheets

这件事改变了两个不同列的状态,这些列依赖于彼此。值。我希望它只在更改位于这两列时触发脚本。这个电子表格上有大约30个人,我不希望每次编辑单元格时都激活它。请看一看,请注意我是一个完整的新手,他用Googling拼凑了这个。

function onEdit(e) {
  var s = e.source.getActiveSheet();
  var data = s.getDataRange().getValues();
  var data_len = data.length;

  var headers = s.getRange(1, 1, 1, s.getLastColumn()).getValues();
  var edit_headers = headers[0].indexOf('Edit');
  var qc_headers = headers[0].indexOf('QC');

  for(var i=0; i<data_len; i++) {
    var edit = data[i][edit_headers];
    var qc = data[i][qc_headers];
    var edit_stat =  s.getRange(i+1,edit_headers +1);
    var qc_stat =  s.getRange(i+1,qc_headers +1);

//Statuses for QC and Edit that change each other
    var stat_1 = "Needs QC";
    var stat_2 = "Pass";
    var stat_3 = "Fail";
    var stat_4 = "Fail Fix in Process";
    var stat_5 = "Re-QC";

//Switch instead of elseif
    switch (edit + qc) //edit + qc stats generate cases below
{
      case stat_1: //Needs QC + ""
        qc_stat.setValue(stat_1); //qc = Needs QC
        break;

      case stat_1 + stat_2: //Needs QC + Pass
        edit_stat.setValue(stat_2); //edit = Pass
        break;  

      case stat_1 + stat_3: //Needs QC + Fail
        edit_stat.setValue(stat_3); //edit = Fail
        break;  

      case stat_4 + stat_3: //Fail Fix in Process + Fail
        qc_stat.setValue(stat_4); //qc = Fail Fix in Process
        break;  

      case stat_1 + stat_4: //Needs QC + Fail Fix in Process
        qc_stat.setValue(stat_5); //qc = Re-QC
        break;   

//Below are fail safes
      case stat_2 + stat_3: //Pass + Fail; just in case qc Passes a fail
        edit_stat.setValue(stat_3); //edit = Fail
        break; 
      case stat_3 + stat_2: //Fail + Pass; just in case qc Fails a Pass
        edit_stat.setValue(stat_2); //edit = Pass
        break; 
}
}    
} 

1 个答案:

答案 0 :(得分:0)

您可以构建一个if语句来检查正在编辑的列,如果该列与允许触发脚本的列不匹配,则返回(退出)脚本(在这种情况下,indexOf将返回-1)。例如:让我们说你只想让第3列和第6列触发脚本,然后像这样做:

function onEdit(e) {
 var allowedCols = [3, 6];
 if (allowedCols.indexOf(e.range.columnStart) === -1) return;
 //rest of your code..
 ...
 }

编辑:如果您还要排除某些标签(请参阅评论中的问题),您可以尝试:

function onEdit(e) {
 var allowedCols = [3, 6];
 var disallowedTabs = ['Sheet3', 'Sheet5'];
 if (allowedCols.indexOf(e.range.columnStart) === -1 || disallowedTabs.indexOf(e.source.getActiveSheet().getName() > -1) return;
 //rest of your code..
 ...