当范围的总和为零时隐藏行

时间:2019-01-09 23:10:15

标签: google-apps-script

在下面的代码中,我想计算一个范围的总和,然后在总和为零(或范围为空)时隐藏一行或多行。

代码正在运行,但未显示预期结果,因为当范围中所有工作表都为空白时,行不会隐藏。

function Ocultar() {  
    var ss = SpreadsheetApp.getActiveSheet();   
    var sum = 0;   
    var range = ss.getRange('Z3:AA10');   
    for(var i in range[0]){   
        sum += range[0][i];   
    }   
    return sum   
    if (sum = 0){   
        ss.getRange('3:10').activate();   
        ss.getActiveSheet().hideRows(ss.getActiveRange().getRow(), ss.getActiveRange().getNumRows());   
    }   
};

1 个答案:

答案 0 :(得分:0)

尝试一下:

function Ocultar(displaydata) {  
  var displaydata=displaydata || true;//change this to false to avoid displaying data by default
  var ss = SpreadsheetApp.getActive();   
  var sh=ss.getActiveSheet();
  var sum=0;   
  var rg=sh.getRange('Z3:AA10');   
  //var rg=sh.getRange('A3:J10');//used for debug
  //rg.setBackground('#ffff00');//used for debug
  var vA=rg.getValues();
  var n=0;//total count
  var nA=0;//string
  var n1=0;//numbers
  var nU=0;//undefined
  var nBlank=0;//blanks
  var typeA=[];
  var isBlank=false;
  for(var i=0;i<vA.length;i++){
    for(var j=0;j<vA[i].length;j++){
      isBlank=false;
      n++;
      switch(typeof(vA[i][j])) {
        case "number":     
          n1++;
          sum+=vA[i][j];
          break;
        case "string":
          nA++;
          if(vA[i][j].length==0){
            nBlank++;
            isBlank=true;
          }
          break;
        case "undefined":
          nU++;
          break;
      }
      var typeObj={n:n,nA:nA,n1:n1,nU:nU,nBlank:nBlank,type:typeof(vA[i][j]),value:vA[i][j],isBlank:isBlank?"TRUE":"FALSE"};
      typeA.push(typeObj);
    }
  }
  if (sum==0 || n==nBlank){   
    sh.hideRows(3, 8);
  }
  if(displaydata){
    var html='';
    for(var i=0;i<typeA.length;i++){
      html+=Utilities.formatString('<br />n: %s, nA: %s n1: %s nU: %s nBlank:%s typeof: %s value: %s isBlank: %s',typeA[i].n,typeA[i].nA,typeA[i].n1,typeA[i].nU,typeA[i].nBlank,typeA[i].type,typeA[i].value,typeA[i].isBlank);
    }
    html+=Utilities.formatString('<br />Sum: %s Cells: %s Strings: %s Numbers: %s Undefined: %s Blanks: %s',sum,n,nA,n1,nU,nBlank);
    var userInterface=HtmlService.createHtmlOutput(html).setWidth(1000).setHeight(500);
    SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Ocultar');
  }
}