Calculate sum of row but its initial row number and row count

Viewed 37

Let's say I have a column of numbers:

1
2
3
4
5
6
7
8

Is there a formula that can calculate sum of numbers starting from n-th row and adding to the sum k numbers, for example start from 4th row and add 3 numbers down the row, i.e. PartialSum(4, 3) would be 4 + 5 + 6 = 15

BTW I can't use App Script as now it has some type of error Error code RESOURCE_EXHAUSTED. and in general I have had issue of stabile work with App Script before too.

1 Answers

As Tanaike mentioned, the error code when using Google Apps Script was just a temporary bug that seems to be solved at this moment.

Now, I can think of 2 possible solutions for this using custom functions:

Solution 1

If your data follows a specific numeric order one by one just like the example provided in the post, you may want to consider using the following code:

function PartialSum(n, k) {
  let sum = n;
  for(let i=1; i<k; i++)
  {
    sum = sum + n + i;
  }
  return sum;
}

Solution 2

If your data does not follow any particular order and you just want to sum a specific number of rows that follow the row you select, then you can use:

function PartialSum(n, k) {
  let ss = SpreadsheetApp.getActiveSheet();
  let r = ss.getRange(n, 1); // Set column 1 as default (change it as needed)
  let sum = n;
  for(let i=1; i<k; i++)
  {
    let val = ss.getRange(n + i, 1).getValue();
    sum = sum + val;
  }
  return sum;
}

Result:

enter image description here

References:

Related