google-sheetsgoogle-apps-scriptsum

How to sum up to a specific value in Google Sheets


I have a complicated situation in Google Sheets and I don't know if it there is a possible solution for this in sheets. I have a list of records with various values both positive and negative, the sum of the positive numbers will always exceed the sum of the negative numbers by a large amount. These are the values in Column A and B

I need to do the following:

  1. sum entire column B (Values) to get the total
  2. using only the records which have positive values, get a list of which records to use to get me closest to the to the sum (the value should exceed the sum and the last record would be reduced to get me to the correct amount) as shown in Column D and E on the screenshot
  3. The return I need is the list of the record names and the values to to use for each record, column A will always have unique names

I am currently doing this manually by sorting and just selecting the data like I have done in Column D and E, but there are a lot of other steps that need to happen after this and I'd ideally like to automate this part.

Any solutions would be appreciated

Sample Data

I have researched this but can't find an exact solution. I have written basic apps-scripts in the past but I mostly use and prefer using formulas because of privacy but I am not finding something that fits this situation, so probably need a script

Here is a sample of the what the input data would look like so you can work with it

Record Name Value
Record 1 97867
Record 2 34653
Record 3 23456
Record 4 12132
Record 5 5778
Record 6 5688
Record 7 5675
Record 8 5456
Record 9 3423
Record 10 2435
Record 11 2235
Record 12 1232
Record 13 801
Record 14 342
Record 15 325
Record 16 324
Record 17 -21
Record 18 -34
Record 19 -3254
Record 20 -4356

The expected output would look something similar to this:

Record Name Value Use Record? Value if used
Record 1 97867 Yes 97867
Record 2 34653 Yes 34653
Record 3 23456 Yes 23456
Record 4 12132 Yes 12132
Record 5 5778 Yes 5778
Record 6 5688 Yes 5688
Record 7 5675 Yes 5675
Record 8 5456 Yes 5456
Record 9 3423 Yes 3423
Record 10 2435 Yes 29
Record 11 2235 No
Record 12 1232 No
Record 13 801 No
Record 14 342 No
Record 15 325 No
Record 16 324 No
Record 17 -21 No
Record 18 -34 No
Record 19 -3254 No
Record 20 -4356 No

Solution

  • What is asked can be done with a plain vanilla spreadsheet formula. Use map(), like this:

    =let(
      start, B2, end, B21,
      map(start:end, lambda(c., let(
        sumToEnd, sum(c.:end),
        if(sumToEnd < 0, hstack("No", iferror(ø)),
        if(sumToEnd - c. < 0, hstack("Yes", sumToEnd),
        hstack("Yes", if(sumToEnd - c. < 0, sumToEnd, c.))))
      )))
    )
    

    The formula will create the whole result table in one go. See map().

    screenshot