【问题标题】:Custom Google Sheets function to find position of subtotal自定义 Google 表格功能以查找小计的位置
【发布时间】:2018-04-28 11:23:26
【问题描述】:

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

例如,给定这样的范围:

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(并且永远不会引发错误),并且我已经达到了调试能力的极限。

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

【问题讨论】:

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


    【解决方案1】:

    这个修改怎么样?

    修改点:

    • 我认为错误的原因是total = total + range[position]range[position]。因为当10,12,14,15,18, 3, 8, 9的值放到A1:A8中时,=SUBTOTALPOSITION(A1:A8, 100)给出的range就是[[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 &gt;= sum 变为true。所以返回 2。

    为了消除这个问题,请进行如下修改。

    发件人:

    total = total + range[position];
    

    收件人:

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

    total += range[position][0];
    

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

    【讨论】:

    • 非常感谢!这确实解决了我的问题!
    • @Lee Davis-Thalbourne 很高兴您的问题得到了解决。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-05
    • 1970-01-01
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多