谷歌应用程序脚本重构重复代码

时间:2017-09-12 17:05:57

标签: arrays google-apps-script

更聪明的方法是什么?代码工作正常,但很笨拙。

function removeEmptyPending(){
  for(var row=2;row<=lastRow;row++){
    if( (tkhContact.getRange('A'+row+':A'+row).getValue() == "") &&
        (tkhContact.getRange('C'+row+':C'+row).getValue() == "") &&
        (tkhContact.getRange('D'+row+':D'+row).getValue() == "") &&
        (tkhContact.getRange('E'+row+':E'+row).getValue() == "") &&
        (tkhContact.getRange('F'+row+':F'+row).getValue() == "") &&
        (tkhContact.getRange('G'+row+':G'+row).getValue() == "") &&
        (tkhContact.getRange('H'+row+':H'+row).getValue() == "") &&
        (tkhContact.getRange('I'+row+':I'+row).getValue() == "") && 
        (tkhContact.getRange('J'+row+':J'+row).getValue() == "") && 
        (tkhContact.getRange('K'+row+':K'+row).getValue() == "") &&
        (tkhContact.getRange('L'+row+':L'+row).getValue() == "") &&
        (tkhContact.getRange('M'+row+':M'+row).getValue() == "") &&
        (tkhContact.getRange('N'+row+':N'+row).getValue() == "") &&
        (tkhContact.getRange('O'+row+':O'+row).getValue() == "") &&
        (tkhContact.getRange('P'+row+':P'+row).getValue() == "") &&
        (tkhContact.getRange('Q'+row+':Q'+row).getValue() == "") )
        {  
          tkhContact.deleteRow(row); // tkhContact.getRange('R'+row+':R'+row).setValue("");
        }
  }
}

我需要跳过B栏,因为那里有一个公式,所以它永远不会空白。

2 个答案:

答案 0 :(得分:1)

使用#is_Blank()

function removeEmptyPending(){
  for(var row=lastRow;row>=2;row--){
    if( (tkhContact.getRange('A'+row+':A'+row).isBlank()) &&
        (tkhContact.getRange('C'+row+':Q'+row).isBlank()) &&
      ){  
          tkhContact.deleteRow(row);  //tkhContact.getRange('R'+row+':R'+row).setValue("");
        }
  }
}

答案 1 :(得分:0)

此代码获取从第2行到最后一行的所有数据,包括A到Q列。然后遍历数据。因此,它在一次操作中获取所有数据。需要单独删除行,并且必须从下往上删除它们。这意味着外部“for”循环必须递减计数器。如果从上到下开始删除,则删除最后一行中的行号,更改其行号。

function removeEmptyPending() {
  var data,i,j,L,L2,lastRow,row,thisRow,thisValue;

  data = tkhContact.getRange(2,1,lastRow-1,17).getValues();//Get all the data from row 2 to the last row
  //including column A to column Q

  L = data.length;//The number of inner arrays in the outer array

  for (i=L;i>0,i--){//Loop through all the rows from last to row 2
    thisRow = data[i];//Get one inner array which is one row of data

    L2 = thisRow.length;

    for (j=0;j<L2,j++){//Loop through each element of the inner array which is the column value

      if (j === 1) {continue;} //Skip the second element which is column B

      thisValue = thisRow[j];//The value for this column

      if (thisValue) {continue;}//The value for this cell is not undefined null or empty string so continue

      tkhContact.deleteRow(i+2); // tkhContact.getRange('R'+row+':R'+row).setValue("");
    }
  }
}