数组中每个第N列的总和

时间:2017-06-01 12:54:32

标签: google-apps-script google-sheets

我正在尝试编写一个自定义函数,它会为数组中的每个第N列生成总和。一个例子是:

| ... | ...  | B   | C   | D   | E   | F   | G   | H   | I   | J    |  K  |  L  |  M  |
|-----|------|-----|-----|-----|-----|-----|-----|-----|-----|------|-----|-----|-----|
| 2   | ...  | Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sept | Oct | Nov | Dec |
| 3   | John | 46  | 94  | 47  | 14  | 94  | 93  | 12  | 14  | 45   | 73  | 71  | 17  |
| 4   | Mary | 24  | 52  | 18  | 18  | 95  | 81  | 98  | 49  | 94   | 27  | 22  | 15  |
| 5   | Jane | 77  | 11  | 63  | 10  | 96  | 48  | 40  | 12  | 28   | 91  | 68  | 88  |
| 6   | Carl | 83  | 97  | 25  | 46  | 62  | 36  | 86  | 69  | 52   | 77  | 96  | 37  |

我想要的功能可能是:

=SUM_ARRAY_BY_COLUMNS(B3:M6, 3)

这将对每个第三个步骤的范围求和,从而在这种情况下生成一个包含四个列的数组:

| ... | A   | B   | C   | D   |
|-----|-----|-----|-----|-----|
| 2   | 187 | 201 | 119 | 161 |
| 3   | 94  | 194 | 228 | 64  |
| 4   | 151 | 154 | 100 | 247 |
| 5   | 205 | 144 | 191 | 210 |

我如何做到这一点?

2 个答案:

答案 0 :(得分:0)

如果您使参数r ='有效'它将使用有效范围。否则它必须是A1表示法。

function sumTest()
{
  sumEveryNColumns('active',2)
}

function sumEveryNColumns(r,n)
{
  var n = (typeof(n)!='undefined')?n:1;
  var r = (typeof(r)!='undefined')?r:'active';
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sht = ss.getActiveSheet();
  if(r != 'active')
  {
    var rng = sht.getRange(r);
  }
  else
  {
    var rng = sht.getActiveRange();
  }
  var rngA = rng.getValues();
  var sumA = [];
  if(n>0)
  {
    for(var i=0;i<rngA[0].length;i+=n)
    {
      var sum=0;
      for(var j=0;j<rngA.length;j++)
      {
        sum+=rngA[j][i];
      }
      sumA.push(sum)
    }
  }
  Logger.log(sumA.join(', '));
  SpreadsheetApp.getUi().alert(sumA.join(', '));
}

答案 1 :(得分:0)

尝试此功能:

function getArraySubtotals(array, numColumns)
{
  var result = [];

  var row = [], newRow = [], sum = 0;

  for (var r = 0, h = array.length; r < h; r++)
  {
    row = array[r];
    for (var c = 0, w = row.length; c < w; c++)
    {
      sum += row[c];
      if ((c + 1) % numColumns == 0)
      {        
        newRow.push(sum);
        sum = 0;
      }    
    }
    result.push(newRow);
    newRow = [];
  }

  return result;
}

试试这个测试功能:

function TESTgetArraySubtotals()
{
  var array = 
 [[22, 21, 21, 28, 32, 20, 28, 23, 12, 35, 19, 28],
  [28, 24, 17, 22, 15, 20, 30, 14, 14, 13, 22, 32],
  [26, 24, 18, 35, 11, 32, 34, 18, 14, 24, 15, 35],
  [28, 22, 20, 22, 16, 32, 24, 30, 31, 10, 26, 28],
  [10, 14, 11, 12, 30, 32, 11, 25, 15, 22, 16, 32],
  [19, 32, 20, 16, 30, 20, 12, 21, 21, 20, 15, 27]];

  Logger.log(getArraySubtotals(array, 3));
}

然后将其用作工作表中的自定义功能:

=getArraySubtotals(D11:O16,3)