简体   繁体   中英

How to get separate sums per each separate column by Google Script?

在此处输入图片说明

I want to get sums of numeric values for each separate column in the range. What I do wrong?

  function countNutrients(){
  
  var sh = SpreadsheetApp.getActiveSheet();
  var lastcol = sh.getLastColumn(); //Get last column
  var lastcolval = sh.getRange(1, 1, 1, lastcol).getValues();
  var lastrowval = sh.getRange("C1:C").getValues(); //Trick to get last row
  var lastrow = lastrowval.filter(String).length;   //
  var sumvalues = sh.getRange(2, 14, lastrow, lastcol).getValues();
    (typeof sumvalues === 'number' ? "" : sumvalues);
    Logger.log(sumvalues);
    for (var j = 13; j < lastcolval.length ; j++) {
       var sumcolumnval = sh.getRange(2, [j], lastrow);
       var sum = 0;
       for (var i in sumcolumnval[0]) {
       var sum = sumvalues[0][i] + sum;
     }
     return sum
     Logger.log(sum);
  }
  return sumcolumnval
  
}

Columns on the screenshot and 65 more

enter link description here

CSV example

Sum of Columns With a Script

function sumOfCols() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Sheet14');
  var hA=sh.getRange(1,1,1,sh.getLastColumn()).getValues()[0];
  var sum={};
  hA.forEach(function(h,i){sum[h]=0;});
  var rg=sh.getRange(2,1,sh.getLastRow()-1,sh.getLastColumn());
  var v=rg.getValues();
  v.forEach(function(r,i){r.forEach(function(c,j){sum[hA[j]]+=c;});});
  var html='';
  hA.forEach(function(h,i){html+=Utilities.formatString('<br />%s(sum): %s',h,sum[h]);});
  var ui=HtmlService.createHtmlOutput(html);
  SpreadsheetApp.getUi().showModelessDialog(ui, "Column Sums")
}

Spreadsheet:

在此处输入图片说明

Output Dialog:

在此处输入图片说明

Data(csv):

COL1,COL2,COL3,COL4,COL5,COL6,COL7,COL8,COL9,COL10
1,2,3,4,5,6,7,8,9,10
2,3,4,5,6,7,8,9,10,11
3,4,5,6,7,8,9,10,11,12
4,5,6,7,8,9,10,11,12,13
5,6,7,8,9,10,11,12,13,14
6,7,8,9,10,11,12,13,14,15
7,8,9,10,11,12,13,14,15,16

A function for your particular Application

This will sum just the six columns that you selected

function countNutrients(){
  var sh=SpreadsheetApp.getActiveSheet();
  var hA=sh.getRange(1,14,1,6).getValues()[0];
  var sum={};
  hA.forEach(function(h,i){sum[h]=0;})
  var vA=sh.getRange(2,14,sh.getLastRow()-1,6).getValues();
  vA.forEach(function(r,i){
    r.forEach(function(c,j){
      if(!isNaN(c)) {
        sum[hA[j]]+=c;
      }
    });
  });
  var html="";
  var keys=Object.keys(sum);
  keys.forEach(function(k,i){
    html+=Utilities.formatString('<br />sum[%s]=%s',k,sum[k]);
  })
  var ui=HtmlService.createHtmlOutput(html);
  SpreadsheetApp.getUi().showModelessDialog(ui,'Sums of Cols N through S')
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM