Home > front end >  How to subtract range from last non empty cell to first?
How to subtract range from last non empty cell to first?

Time:09-10

I am a beginner in google sheets and I couldn't get around this formula. I have range of cells and I want to subtract last non empty cell to first cell (Z-A), here is the image:

Subtract values

As the values are updated in columns C, D, E and so on. I want to get the last non empty cell (from right) and subtract the values by moving backward (left). Like this:

sub = 10(Column G)-0(Column F)-10(Column E)-0(Column D)-10(Column C)

Can we devise a formula which will get the last non empty cell and subtract values until the first value? Here is the enter image description here

CodePudding user response:

Suggestion: Use a custom function

You may use the following script as a custom function to get the difference between the value of the last cell and the sum of the other cells:

function SUBTRACTFROMLASTNUMBER(data) { //you can rename the custom function name
  var sum = 0;
  var data2 = data[0].filter(x => {
    return (x != "") ? x : null;
  }); //filtered data
  var lastNumber = data2.pop(); //last number
  data2.map(x => sum  = x); //sums the remaining values
  return (lastNumber - sum); //returns the output
}

This custom function extracts the selected data from the sheet and then separates the value of the last cell using pop() and then filters and sums the remaining data using filter() and map() and then subtracts the sum from the value of the last cell.

Usage

You may use this function as:

=SUBTRACTFROMLASTNUMBER(<range>) enter image description here

Reference:

  • Related