Reputation: 10534
I want to add content to last row of a particular column.
For example current state of my google sheet is
x A B C
1 value1ofA value1ofB value1ofC
2 value2ofA value2ofB value2ofC
3 value3ofB value3ofC
4 value4ofC
Sometime I want to add value value5ofC
in column C
Sometime I want to add value value4ofB
in column B
Sometime I want to add value value3ofA
in column A
I know how to insert value in single cell using range
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getSheets()[0];
sheet.getRange(5, 5).setValue('value5ofC') // This will set content at cell of 5th row and 5th column
In this sample code I know location of last cell of column C, If I want to automate it I want to find out location of last cell so I can fill it with some content.
I can find out last row of whole sheet using sheet.getLastRow()
But I want last row of particular column.
How can I find location of last cell of any column?
Upvotes: 1
Views: 1227
Reputation: 201378
If my understanding for your question is correct, how about this answer? I think that there are several solutions for your situation. So please think of these as 3 of them.
In this sample script, it retrieves the last row of specific column by giving the column letter. As a sample, the last row of column "C" is retrieved.
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getSheets()[0];
var col = "C"; // Please input the column letter.
var res = sheet.getRange(col + ":" + col).getValues().filter(String).length;
Logger.log(res)
When this script is used for your sample table, 4 is returned.
In this sample script, it retrieves the last rows of all columns. At first, all values of cells are retrieved. Then, the array including the values is transposed, and the last rows are retrieved.
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getSheets()[0];
var values = sheet.getDataRange().getValues();
var res = values[0].map(function(_, i) {return values.map(function(r) {return r[i]}).filter(String).length});
Logger.log(res)
When this script is used for your sample table, an array of [2.0, 3.0, 4.0]
is returned. In this case, the index of array means the column index. So in this case, the last rows of column "A", "B" and "C" mean 2, 3, and 4, respectively.
Pattern 1 and 2 can use to the sheet that all cells of the column are filled by values. From your sample table, I proposed above 2 patterns. But if you want to retrieve the last row of the column including empty cells, you can use the script like below.
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getSheets()[0];
var col = "C";
var values = sheet.getRange(col + ":" + col).getValues();
var lastRow;
for (var i = values.length - 1; i >= 0; i--) {
if (values[i][0]) {
lastRow = i + 1;
break;
}
}
Logger.log(lastRow)
If I misunderstand your question, please tell me. I would like to modify it.
Upvotes: 2