简体   繁体   中英

How to I calculate the sum of the last 7 rows, for each row, inside an ArrayFormula?

I have a column D with numerical values and on an adjacent column, I want to display the sum for the last 7 rows relative to the current row.

I've tried a couple of variants, most of them inspired by StackOverflow and other sites but they haven't worked as I need them.

I figured that since Offset() creates a range it would be simple to just "slice" the range I need and feed it to sum()

ArrayFormula( Sum(Offset(D7:D500,-6,1,7,1)) )

However, it seems that it only calculates the cell I place this formula in.

I adapted a potential solution I found online to my situation

ArrayFormula(SUMIF(ROW(D7:D500),"<="&ROW(D7:D500),D7:D500))

This one calculates the sum for all the previous rows, so I figured using SUMIFS() would get me what I need, therefore

=ArrayFormula(SUMIFS(D7:D500, ROW(D7:D500),"<="&ROW(D7:D500), ROW(D7:D500),">"&ROW(D7:D500)-7))

But this one just doesn't work. I've also tried creating the range with Address() and Interpret() but it seems they don't work properly inside ArrayFormula()

I'm fairly new at it so it might just be that I'm not using them properly. What am I doing wrong here? Is there a better way of doing this? I would rather use ArrayFormula() if possible since the formula will live in a single cell.

method 1. OFFSET function

COUNT(D7:D500)-7 tells EXCEL how many cells to step down from D7 .

=SUM(OFFSET(D7:D500,COUNT(D7:D500)-7,,7,1))

no Ctrl + Shift + Enter

method 2. Index function

If you concern the volatileness of the OFFSET function, you may try

=SUM(INDEX(D7:D500,COUNT(D7:D500)-6):INDEX(D7:D500,COUNT(D7:D500)))

no Ctrl + Shift + Enter

try:

=SUM(IFERROR(QUERY(D7:D500, "limit 7 offset "&COUNTA(D7:D500)-7)))

0

You can accomplish this via a custom function created in Google Apps Script. To achieve this, follow these steps:

  • In your spreadsheet, select Tools > Script editor to open a script bound to your file.
  • Copy this function in the script editor, and save the project:
function SUM7ROWS(input) {
  var output = [];
  var sum;
  for (var row = 0; row < input.length; row++) {
    sum = 0;
    for (var i = 6; i >= 0; i--) {
      if (row - i >= 0) {
        sum = sum + Number(input[row - i]);
      }
    }
    output.push(sum);
  }
  return output;
}
  • Now, if you go back to your spreadsheet, you can use this function just as you would do with any other function. You just have to provide the appropriate range as a parameter (in this case it would be D7:D500 ), as you can see here:

在此处输入图片说明

I hope this is of any help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM