Selecting the last value of a column

前端 未结 23 1879
再見小時候
再見小時候 2020-11-28 19:15

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 li

23条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-28 19:33

    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.

提交回复
热议问题