使用谷歌应用程序脚本对列函数中的所有行求和



我有一列"Net Sales",我试图在谷歌工作表中对该列中的所有值求和,但使用谷歌应用程序脚本。净销售额的数据会发生变化,所以我尽量抽象。这是我到目前为止的函数,总和的输出显示在一个单独的电子表格中。这个函数并没有把所有的销售额加起来,而是把所有的数字加在一起。例如,如果列"净销售额"中的行是100、200和50,则输出将是10020050,而不是350。如何获得一个函数来将数字相加?


//sum of all net sales (not working)
var netSquare = sheet_origin2.getRange(2, 12, sheet_origin2.getLastRow(), 1).getValues();
var sum = 0;
for (var i=0; i<=sheet_origin2.getLastRow(); i++) {
sum += netSquare[i];
}
sheet_destination.getRange(sheet_destination.getLastRow(), 2, 1, 1).setValue(sum);

  1. 最后一行≠行数,尤其是因为您正在跳过第一行
  2. .getValues()返回一个二维数组,因此需要使用netSquare[i][0]
  3. 您应该在for循环中使用正在迭代的数组的长度,并确保索引不会越界
function sum() {
// ... define the sheets ...
var lastRow = sheet_origin2.getLastRow();
var numRows = lastRow - 1; // Subtract one since you're skipping the first row
var netSquare = sheet_origin2.getRange(2, 12, numRows, 1).getValues();
var sum = 0;
for (var i=0; i<netSquare.length; i++) {
sum += netSquare[i][0];
}
sheet_destination.getRange(sheet_destination.getLastRow(), 2, 1, 1).setValue(sum);
}

计算和的一种更有效的方法是使用reduce,这样就可以消除for循环

仅用reduce函数就可以计算出总和。所有其他函数:flatmapfilter用于确保数据正确,因为我们不知道您的电子表格文件是如何构建的,也不知道您使用的值是什么。有关每个步骤的详细说明,请参阅代码注释。

解决方案:

const netSquare = sheet_origin2.getRange('L2:L').getValues(). // get column L (12th column)
flat(). // convert the 2D array to 1D array
filter(v=>v!=''). // filter out empty cells
map(v=>parseInt(v)); // convert string numbers to integers
const sum = netSquare.reduce((a,b)=>a+b); // add all numbers together
sheet_destination.getRange(sheet_destination.getLastRow(), 2, 1, 1).setValue(sum);

对于这个问题,最短的修复方法是键入强制转换,因为它们在获取数据时变成了字符串。

更改您的:

sum += netSquare[i];

至:

sum += parseInt(netSquare[i]); // if whole number
sum += parseFloat(netSquare[i]); // if number has decimal

这将强制netSquare[i]值的类型为integer/float,该类型可以作为数字添加。当我们确定netSquare[i]值都是数字时,就不会有问题。

对于可能的问题,可以在键入非数字数据时检查可能的结果。

最新更新