如何使用谷歌应用程序脚本中的范围? [英] How to use for to sum a range in google app script?
问题描述
$ b
函数somaDias(范围,天数) {
var sum = 0; (i = 0; i <天; i ++){
sum = sum + range [i];
。
}
返回soma;
}
我将在一个报告中使用这个函数,本月的每一天。我们的想法是选择整列值,将其作为范围传递,并将这些值累加到该月的某一天。我知道有一些问题,因为这是一个错误。
sum = sum + range [i];
因为当我用只有1的列进行测试时...返回值是0111111
= somaDias(C9:C15; 6)//应返回6,但返回0111111
我不想使用= sum(),因为范围根据当天而变化。我想通过月份的30天范围,然后传递我想要总结的天数。如果我用sum,我必须每天重新选择范围....
我做错了什么?
为什么不使用函数 SUM()
中内置的电子表格? (doc 此处)
编辑下面的评论。
我不喜欢自定义函数,但这是一种实现你想要的方法:只使用1参数=天数,它会从第一列开始计数。
函数somaDias(天){
var sum = 0;
var sh = SpreadsheetApp.getActiveSheet();
var values = sh.getRange(sh.getActiveCell()。getRowIndex(),1,1,days).getValues();
for(var i in values [0]){
sum + = values [0] [i];
}
回报金额;
}
I want create a simple custom sum formula in google Spreadsheets using google app Script.
function somaDias(range, days) {
var sum = 0;
for(i=0; i<days; i++){
sum = sum + range[i];
}
return soma;
}
I will use this function in a report that has a column with monetary values for each day of the month. The idea is to select the whole column of values, pass it as a range and them sum this values up to a day of the month. I know there is something wrong with
sum = sum + range[i];
because, when I test it with a column that has only 1... the return is "0111111"
=somaDias(C9:C15;6) // should return 6, but it returns 0111111
I don´t want to use =sum(), because the range changes according to the day. I want to pass as the range the 30 days of the month and then pass the number of days I want to sum. If I used sum, I would have to reselect the range everyday....
What I´m doing wrong?
Why not using the spreadsheet built in function SUM()
? (doc here)
edit following comment.
I don't like custom functions but here is a way to achieve what you want : use only 1 parameter = number of days, it will count from the first column.
function somaDias(days) {
var sum = 0;
var sh = SpreadsheetApp.getActiveSheet();
var values = sh.getRange(sh.getActiveCell().getRowIndex(),1,1,days).getValues();
for(var i in values[0]){
sum += values[0][i];
}
return sum;
}
这篇关于如何使用谷歌应用程序脚本中的范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!