自定义Google表格功能可查找小计

时间:2018-04-28 11:23:27

标签: google-apps-script google-sheets custom-function

我目前正在尝试为google工作表编写一个自定义函数,给定一维范围,告诉我累积金额达到(或超过)给定总数的位置,或者抛出错误累积金额永远不会达到给定的总和。

作为一个例子,考虑到这样的范围:

10
12
14
15
18
 3
 8
 9

如果要求的金额为" 24",则该函数将返回3.

如果要求的金额为" 60",则该函数将返回5.

如果请求的总和是" 1000",则该函数会抛出错误。

我目前坚持的代码是:

function SUBTOTALPOSITION(range,sum)
{
 /**
 * Finds the position in a one-dimensional range where
 * the cumulative sum reaches the requested subtotal
 *
 * @range The range being searched (1-dimensional range only)
 * @sum The cumulative sum being searched for
 * @customfunction
 */
  if((range.length > 1) && (range[0].length > 1))
  {
    throw 'range is multi-dimensional';
  }

  var position = 0;
  var total = 0;
  while(position < range.length)
  {
    total = total + range[position];
    position++;

    if(total >= sum)
    {
      return position;
    }
  }
  throw 'Sum not reached';
}

我已经达到了 位置的地步,但不是正确的位置。如果我给出的数量等于或小于范围中的第一个数字,它会正确返回1,但是给定的任何其他数字总是返回2(并且永远不会抛出错误),并且我达到了调试能力的极限

在这段代码中哪里出错了?或者有更好的方法来解决这个问题吗?这可以在没有自定义功能的情况下完成吗?

1 个答案:

答案 0 :(得分:1)

这次修改怎么样?

修改点:

  • 我认为错误的原因是&& range[position]。因为当total = total + range[position]的值被10,12,14,15,18, 3, 8, 9 A1:A8时,range给出的=SUBTOTALPOSITION(A1:A8, 100)[[10.0], [12.0], [14.0], [15.0], [18.0], [3.0], [8.0], [9.0]]。这是二维数组。 range[position]是一个对象。因此,在这种情况下,运行total = total + range[position]时,total将用作字符串。这样,数组的每个元素总和为0101214...之类的字符串。结果,当sum为1000时,total在第二个循环变为01012total >= sum变为true。所以返回2。

要删除此问题,请修改如下。

来自:

total = total + range[position];

致:

total = total + range[position][0];

total += range[position][0];

如果我误解了你的问题,我很抱歉。