Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting the last value of a column

I have a spreadsheet with some values in column G. Some cells are empty in between, and I need to get the last value from that column into another cell.

Something like:

=LAST(G2:G9999) 

except that LAST isn't a function.

like image 865
cambraca Avatar asked Nov 12 '10 23:11

cambraca


People also ask

How do I find the last cell value in Excel?

The easiest way to find the last cell with value in a row is using keyboard command. Click on the first cell of the row and press CTRL+ Right Arrow Key. Your cursor will move to the last non-empty cell in that row.


2 Answers

Similar answer to caligari's answer, but we can tidy it up by just specifying the full column range:

=INDEX(G2:G, COUNT(G2:G)) 
like image 114
dohmoose Avatar answered Oct 09 '22 04:10

dohmoose


So this solution takes a string as its parameter. It finds how many rows are in the sheet. It gets all the values in the column specified. It loops through the values from the end to the beginning until it finds a value that is not an empty string. Finally it retunrs the value.

Script:

function lastValue(column) {   var lastRow = SpreadsheetApp.getActiveSheet().getMaxRows();   var values = SpreadsheetApp.getActiveSheet().getRange(column + "1:" + column + lastRow).getValues();    for (; values[lastRow - 1] == "" && lastRow > 0; lastRow--) {}   return values[lastRow - 1]; } 

Usage:

=lastValue("G") 

EDIT:

In response to the comment asking for the function to update automatically:

The best way I could find is to use this with the code above:

function onEdit(event) {   SpreadsheetApp.getActiveSheet().getRange("A1").setValue(lastValue("G")); } 

It would no longer be required to use the function in a cell like the Usage section states. Instead you are hard coding the cell you would like to update and the column you would like to track. It is possible that there is a more eloquent way to implement this (hopefully one that is not hard coded), but this is the best I could find for now.

Note that if you use the function in cell like stated earlier, it will update upon reload. Maybe there is a way to hook into onEdit() and force in cell functions to update. I just can't find it in the documentation.

like image 23
tinifni Avatar answered Oct 09 '22 04:10

tinifni