How to find the last column in a particular row in Google Spreadsheet using Google Apps Script

Hello everyone. This is my first medium post and I am going to show you how you can find the last column(filled) in a particular row in a Google Spreadsheet. Well it is very much easier to find the last column of a sheet but it’s a bit tricky to find the last column of each row especially when the last column changes with each row.

Here’s is an example of such a case.

Image for post
Image for post

Here the isBlank() method of Class Range becomes handy.

So at first you just call the active sheet and find the Lastrow of the sheet as shown below;

var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(“Sheet1”);
var lr = sheet.getLastRow();

Once you get the Lastrow of the sheet just add a simple For loop and compute the last column of each row using a While loop as shown below:

for( var k = 2; k <= lr ; k++) {

var m = 1; //simply set a variable with value 1
while( sheet.getRange(k,m).isBlank() == false) {

m = m +1;


}
var lc = m; //gives you the last column from each row.

That’s all. You can use this piece of code if you want ;)

Feel free to share your feedback after all this is my first medium post.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store