[英]How can I sum the values of cells in a row more efficiently?
Hello I've searched and tried for a long time but I just can't get it.您好,我已经搜索并尝试了很长时间,但我就是无法得到它。 On the picture you can see my Google Sheet.在图片上你可以看到我的谷歌表格。
I just want to add up all the numbers in the row that are <= 10.我只想将<= 10的行中的所有数字相加。
How can I simplify the code from below?如何从下面简化代码? Does anyone have an idea?有人有想法吗? Many thanks!非常感谢!
function calculationFirstColumn() { var sheet = SpreadsheetApp.getActiveSheet(); var originalData = sheet.getRange(2, 2, sheet.getLastRow() -1, 1).getValues(); var filteredItems = originalData.filter(function(x){return x==1}).length; var filteredItems2 = originalData.filter(function(x){return x==2}).length; var filteredItems3 = originalData.filter(function(x){return x==3}).length; var filteredItems4 = originalData.filter(function(x){return x==4}).length; var filteredItems5 = originalData.filter(function(x){return x==5}).length; var filteredItems6 = originalData.filter(function(x){return x==6}).length; var filteredItems7 = originalData.filter(function(x){return x==7}).length; var filteredItems8 = originalData.filter(function(x){return x==8}).length; var filteredItems9 = originalData.filter(function(x){return x==9}).length; var filteredItems10 = originalData.filter(function(x){return x==10}).length; var total = filteredItems+filteredItems2+filteredItems3+filteredItems4+filteredItems5+ filteredItems6+filteredItems7+filteredItems8+filteredItems9+filteredItems10; sheet.getRange("B18").setValue(total); }
You do not need to use filters, instead use a combination of a loop and conditional statement:您不需要使用过滤器,而是使用循环和条件语句的组合:
function calculationFirstColumn() {
var sheet = SpreadsheetApp.getActiveSheet();
var originalData = sheet.getRange(2, 2, sheet.getLastRow() -1, 1).getValues();
var total = 0;
for (var i = 0; i < originalData.length; i++){
if(originalData[i][0] <= 10){
total += originalData[i][0];
}
Logger.log(total);
}
sheet.getRange("B18").setValue(total);
}
is a script really necessary for something like this?像这样的事情真的需要脚本吗?
=SUMIF(B2:B,"<=10",B2:B) =SUMIF(B2:B,"<=10",B2:B)
@ziganotschka ThankYOU! @ziganotschka谢谢! Your last answer works.你的最后一个答案有效。 But I still have an understanding question.但我仍然有一个理解问题。
original data .原始数据。 The area to be evaluated is clearly defined and there is no empty cell in it.要评估的区域明确定义,其中没有空单元格。 Then why does this function need the instruction?那为什么这个 function 需要指令呢?
if(originalData[i][0] <= 10 /*&& originalData[i][0] !=''*/){ total ++; }
Which cells does this function count without this additional line?如果没有此附加行,此 function 计数哪些单元格?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.