Determining the last row in a single columnGoogle Sheets Script Count formulaIn a given column, how do I find the last cell that has a value?count empty values in arrayFind LastRow of column C (when Col A and B have a different row size)?remove trailing elements from array that are equal to zero - better wayHow to get the value of last row of google spreadsheet using google app scriptDate Validation with If/Then Function in Google Apps ScriptGAS How to use getDataRange and getLastRow when the sheet contains full column arrayformulas in a dynamic spreadsheetScript suggestion to insert a timestamp when button is pressedUse PHPexcel to find highest non-empty column/row cheaply (on Google Sheets export)Assign different user for editing rows based on criteria in Google spreadsheetCopy a row to new sheet based on value in a cellFiltering with newest version of rows in three different sheetsScript for Google sheets (auto email function)Google script equivalent for Excel script to last column in row offset by oneSheets Forms Data Manipulation and Deleting Rows if Certain Cells are BlankHow can I sort a specific dynamic range?Searching a Google Form response (Google Sheets) for row and column numbersScript copies row data to another sheet, is only partially workingget all rows in a sheet with data where a specific column is empty using Google Apps Scripts
How do some PhD students get 10+ papers? Is that what I need for landing good faculty position?
Do beef farmed pastures net remove carbon emissions?
Generate Brainfuck for the numbers 1–255
How far did Gandalf and the Balrog drop from the bridge in Moria?
In which case does the Security misconfiguration vulnerability apply to?
What kind of liquid can be seen 'leaking' from the upper surface of the wing of a Boeing 737-800?
Why are Tucker and Malcolm not dead?
How much can I judge a company based on a phone screening?
Programmatically add log information in all renderings(controller, view) html
A torrent of foreign terms
How to remove ambiguity: "... lives in the city of H, the capital of the province of NS, WHERE the unemployment rate is ..."?
Simplification of numbers
Why command hierarchy, if the chain of command is standing next to each other?
Why aren't rainbows blurred-out into nothing after they are produced?
What is the farthest a camera can see?
Are those flyers about apartment purchase a scam?
How do I call a 6 digit Austrailian phone number with a US based mobile phone?
crippling fear of hellfire &, damnation, please help?
Does Nightpack Ambusher's second ability trigger if I cast spells during the end step?
A continuous water "planet" ring around a star
(A room / an office) where an artist works
How exactly are corporate bonds priced at issue
Authors on the Credibility and Corruption of Modern Science
When does Tiana, Ship's Caretaker check card type?
Determining the last row in a single column
Google Sheets Script Count formulaIn a given column, how do I find the last cell that has a value?count empty values in arrayFind LastRow of column C (when Col A and B have a different row size)?remove trailing elements from array that are equal to zero - better wayHow to get the value of last row of google spreadsheet using google app scriptDate Validation with If/Then Function in Google Apps ScriptGAS How to use getDataRange and getLastRow when the sheet contains full column arrayformulas in a dynamic spreadsheetScript suggestion to insert a timestamp when button is pressedUse PHPexcel to find highest non-empty column/row cheaply (on Google Sheets export)Assign different user for editing rows based on criteria in Google spreadsheetCopy a row to new sheet based on value in a cellFiltering with newest version of rows in three different sheetsScript for Google sheets (auto email function)Google script equivalent for Excel script to last column in row offset by oneSheets Forms Data Manipulation and Deleting Rows if Certain Cells are BlankHow can I sort a specific dynamic range?Searching a Google Form response (Google Sheets) for row and column numbersScript copies row data to another sheet, is only partially workingget all rows in a sheet with data where a specific column is empty using Google Apps Scripts
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I have a sheet with data in cols A through H.
I need to determine the last row in column A that contains data (it's all contiguous - no gaps in the data/rows).
There is also data in the other columns that have more rows of data than column A, so I need to isolate only column A. (And/or just a range within col A).
I can do this on the spreadsheet level using
=COUNTA(A2:A100)
However in all of my researching for a Google Apps Script solution, all I seem to find are requirements to perform multiple functions encompassing dozens of lines of code - including plenty of i++ stuff... Which I could do less complexly via offsetting directly from A1.
Is there possibly a column-specific way of modifying this method?
var aLast = ss.getDataRange().getNumRows();
If a convoluted process is what is required, then so be it. But I find it difficult to imagine (and even more difficult to find!) a simpler solution.
Does anyone care to enlighten me (or pop my bubble)?
google-apps-script google-sheets
add a comment |
I have a sheet with data in cols A through H.
I need to determine the last row in column A that contains data (it's all contiguous - no gaps in the data/rows).
There is also data in the other columns that have more rows of data than column A, so I need to isolate only column A. (And/or just a range within col A).
I can do this on the spreadsheet level using
=COUNTA(A2:A100)
However in all of my researching for a Google Apps Script solution, all I seem to find are requirements to perform multiple functions encompassing dozens of lines of code - including plenty of i++ stuff... Which I could do less complexly via offsetting directly from A1.
Is there possibly a column-specific way of modifying this method?
var aLast = ss.getDataRange().getNumRows();
If a convoluted process is what is required, then so be it. But I find it difficult to imagine (and even more difficult to find!) a simpler solution.
Does anyone care to enlighten me (or pop my bubble)?
google-apps-script google-sheets
add a comment |
I have a sheet with data in cols A through H.
I need to determine the last row in column A that contains data (it's all contiguous - no gaps in the data/rows).
There is also data in the other columns that have more rows of data than column A, so I need to isolate only column A. (And/or just a range within col A).
I can do this on the spreadsheet level using
=COUNTA(A2:A100)
However in all of my researching for a Google Apps Script solution, all I seem to find are requirements to perform multiple functions encompassing dozens of lines of code - including plenty of i++ stuff... Which I could do less complexly via offsetting directly from A1.
Is there possibly a column-specific way of modifying this method?
var aLast = ss.getDataRange().getNumRows();
If a convoluted process is what is required, then so be it. But I find it difficult to imagine (and even more difficult to find!) a simpler solution.
Does anyone care to enlighten me (or pop my bubble)?
google-apps-script google-sheets
I have a sheet with data in cols A through H.
I need to determine the last row in column A that contains data (it's all contiguous - no gaps in the data/rows).
There is also data in the other columns that have more rows of data than column A, so I need to isolate only column A. (And/or just a range within col A).
I can do this on the spreadsheet level using
=COUNTA(A2:A100)
However in all of my researching for a Google Apps Script solution, all I seem to find are requirements to perform multiple functions encompassing dozens of lines of code - including plenty of i++ stuff... Which I could do less complexly via offsetting directly from A1.
Is there possibly a column-specific way of modifying this method?
var aLast = ss.getDataRange().getNumRows();
If a convoluted process is what is required, then so be it. But I find it difficult to imagine (and even more difficult to find!) a simpler solution.
Does anyone care to enlighten me (or pop my bubble)?
google-apps-script google-sheets
google-apps-script google-sheets
edited Dec 30 '15 at 6:01
Mogsdad
34.5k12 gold badges102 silver badges212 bronze badges
34.5k12 gold badges102 silver badges212 bronze badges
asked Jul 13 '13 at 16:42
5th4x45th4x4
5016 gold badges15 silver badges23 bronze badges
5016 gold badges15 silver badges23 bronze badges
add a comment |
add a comment |
15 Answers
15
active
oldest
votes
How about using a JavaScript trick?
var Avals = ss.getRange("A1:A").getValues();
var Alast = Avals.filter(String).length;
I borrowed this idea from this answer. The Array.filter() method is operating on the Avals array, which contains all the cells in column A. By filtering on a native function's constructor, we get back only non-null elements.
This works for a single column only; if the range contains multiple columns,then the outcome of filter() will include cells from all columns, and thus be outside the populated dimensions of the range.
6
Very crafty. I look forward to the day when I understand javascript well enough to think as creatively as that. All in due time, I suppose. However in the meantime, I have enjoyed seeing the way you think. And kudos to you for citing the inspiration for your solution. Classy. Thanks yet again.
– 5th4x4
Jul 14 '13 at 12:56
1
Something to point out that is almost certainly obvious to more experienced coders is that the range can not span more than a single column. This was something I didn't quite get, but Mogsdad pointed this out in a comment (that was deleted) that it can't span more than a single column. Again, I just want to put this here for those that are on my experience level and still having trouble grasping some concepts. Thanks, Mogsdad.
– Soundfx4
Dec 30 '15 at 5:57
3
@5th4x4 Clarifying question from a javascript novice: wouldn't that return the number of cells in a row that were non-null, not necessarily the number of the row number of the last cell with content if there was a gap in the above cells somewhere? So something like this while loop could be used to just trim the null elements off the end of the array.
– Scotosaurus
Nov 20 '17 at 21:17
1
@Scotosaurus That's right. However, the question specifically addresses the fact that the data does not have any empty gaps: "it's all contiguous - no gaps in the data/rows", so the answer is correct but will not work on data with gaps.
– dnlmzw
Mar 21 '18 at 8:58
@Mogsdad - I do not believe cells are "null"; they're empty strings [''], at least in my experience
– Peter
Apr 27 at 19:58
|
show 1 more comment
Although there is no straighforward formula, I can think of, it doesn't require dozens of lines of code to find out the last row in column A. Try this simple function. Use it in a cell the normal way you'd use some other function =CountColA()
function CountColA()
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
for(var i = data.length-1 ; i >=0 ; i--)
if (data[i][0] != null && data[i][0] != '')
return i+1 ;
the above returns the last row of the entire worksheet, not col A. I need ONLY the last row of col A in the form of a variable for use within the script itself. Since there is no magic pill for this, I guess I'll just loop down from A1 until I hit (empty) paydirt. Thanks anyway.
– 5th4x4
Jul 13 '13 at 18:06
1
Sorry, it was a small error from my end. Please see the corrected script.
– Srik
Jul 14 '13 at 12:14
add a comment |
You can do this by going in the reverse way.
Starting from the last row in spreadsheet and going up till you get some value. This will work in all the cases even if you have some empty rows in between.
Code looks like below:
var iLastRowWithData = lastValue('A');
function lastValue(column)
var iLastRow = SpreadsheetApp.getActiveSheet().getMaxRows();
var aValues = SpreadsheetApp.getActiveSheet().getRange(column + "2:" + column + lastRow).getValues();
for (; aValues[iLastRow - 1] == "" && iLastRow > 0; iLastRow--)
return iLastRow;
add a comment |
This will get the last row in a sheet assuming based on column A.
function getLastDataRow(sheet)
var lastRow = sheet.getLastRow();
var range = sheet.getRange("A" + lastRow);
if (range.getValue() !== "")
return lastRow;
else
return range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
This fixes @mrityunjay-pandey partially-correct answer.
To extend this answer to get the last row and column, we can use:
function columnToLetter(column)
var temp, letter = '';
while (column > 0)
temp = (column - 1) % 26;
letter = String.fromCharCode(temp + 65) + letter;
column = (column - temp - 1) / 26;
return letter;
function letterToColumn(letter)
var column = 0, length = letter.length;
for (var i = 0; i < length; i++)
column += (letter.charCodeAt(i) - 64) * Math.pow(26, length - i - 1);
return column;
function getLastDataColumn(sheet)
var lastCol = sheet.getLastColumn();
var range = sheet.getRange(columnToLetter(lastCol) + "1");
if (range.getValue() !== "")
return lastCol;
else
return range.getNextDataCell(SpreadsheetApp.Direction.PREVIOUS).getColumn();
function getLastDataRow(sheet)
var lastRow = sheet.getLastRow();
var range = sheet.getRange("A" + lastRow);
if (range.getValue() !== "")
return lastRow;
else
return range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
function run()
var sheet = SpreadsheetApp.getActiveSheet();
var [startRow, lastRow] = [2, getLastDataRow(sheet)];
var [startCol, lastCol] = [1, getLastDataColumn(sheet)];
1
nice! I like those extra functions
– Unreality
Apr 13 at 11:02
add a comment |
For very large spreadsheets, this solution is very fast:
function GoLastRow()
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('A:AC').createFilter();
var criteria = SpreadsheetApp.newFilterCriteria().whenCellNotEmpty().build();
var rg = spreadsheet.getActiveSheet().getFilter().setColumnFilterCriteria(1, criteria).getRange();
var row = rg.getNextDataCell (SpreadsheetApp.Direction.DOWN);
LastRow = row.getRow();
spreadsheet.getActiveSheet().getFilter().remove();
spreadsheet.getActiveSheet().getRange(LastRow+1, 1).activate();
;
add a comment |
To get the number of columns or last column's index:
var numColumns = sheet.getLastColumn()
To get the no of rows or last row's index:
var numRows = sheet.getLastRow()
where
var sheet = SpreadsheetApp.getActiveSheet()
3
this looks at the entire sheet, including empty cells, which doesn't sound like it's what the OP wants.
– Ryan Tuck
Mar 29 '17 at 15:55
add a comment |
This may be another way to go around lastrow.
You may need to play around with the code to suit your needs
function fill()
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('a1').activate();
var lsr = spreadsheet.getLastRow();
lsr=lsr+1;
lsr="A1:A"+lsr;
spreadsheet.getActiveRange().autoFill(spreadsheet.getRange(lsr), SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
;
add a comment |
var Direction=SpreadsheetApp.Direction;
var aLast =ss.getRange("A"+(ss.getLastRow()+1)).getNextDataCell(Direction.UP).getRow();
Please don't just post code - add an explanation as well.
– CertainPerformance
Jul 23 '18 at 7:32
add a comment |
personally I had a similar issue and went with something like this:
function getLastRowinColumn (ws, column)
var page_lastrow = ws.getDataRange().getNumRows();
var last_row_col = 0
for (i=1; i<=page_lastrow;i++)
if (!(spread.getRange(column.concat("",i)).isBlank())) last_row_col = i;
return last_row_col
It looks for the number of rows in the ws and loops through each cell in your column. When it finds a non-empty cell it updates the position of that cell in the last_row_col variable. It has the advantage of allowing you to have non-contiguous columns and still know the last row (assuming you are going through the whole column).
add a comment |
Never too late to post an alternative answer I hope. Here's a snippet of my Find last Cell. I'm primarily interested in speed. On a DB I'm using with around 150,000 rows this function took (average) 0.087 seconds to find solution compared to @Mogsdad elegant JS solution above which takes (average) 0.53 sec on same data. Both arrays were pre-loaded before the function call. It makes use of recursion to do a binary search. For 100,000+ rows you should find it takes no more than 15 to 20 hops to return it's result.
I've left the Log calls in so you can test it in the console first and see its workings.
/* @OnlyCurrentDoc */
function myLastRow()
var ss=SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var colArray = ss.getRange('A1:A').getDisplayValues(); // Change to relevant column label and put in Cache
var TestRow=ss.getLastRow();
var MaxRow=ss.getMaxRows();
Logger.log ('TestRow = %s',TestRow);
Logger.log ('MaxRow = %s',MaxRow);
var FoundRow=FindLastRow(TestRow,MaxRow);
Logger.log ('FoundRow = %s',FoundRow);
function FindLastRow(v_TestRow,v_MaxRow)
/* Some housekeeping/error trapping first
* 1) Check that LastRow doesn't = Max Rows. If so then suggest to add a few lines as this
* indicates the LastRow was the end of the sheet.
* 2) Check it's not a new sheet with no data ie, LastRow = 0 and/or cell A1 is empty.
* 3) A return result of 0 = an error otherwise any positive value is a valid result.
*/
return !(colArray[0][0]) ? 1 // if first row is empty then presume it's a new empty sheet
:!!(colArray[v_TestRow][0]) ? v_TestRow // if the last row is not empty then column A was the longest
: v_MaxRow==v_TestRow ? v_TestRow // if Last=Max then consider adding a line here to extend row count, else
: searchPair(0,v_TestRow); // get on an find the last row
function searchPair(LowRow,HighRow)(!!(colArray[BinRow][0])) ? searchPair(BinRow+1,HighRow)
: false; // Error
/* The premise for the above logic is that the binary search is looking for a specific pairing, <Text/No text>
* on adjacent rows. You said there are no gaps so the pairing <No Text/Text> is not tested as it's irrelevant.
* If the logic finds <No Text/No Text> then it looks back up the sheet, if it finds <Text/Text> it looks further
* down the sheet. I think you'll find this is quite fast, especially on datasets > 100,000 rows.
*/
add a comment |
I tried to write up 3 following functions, you can test them for different cases of yours. This is the data I tested with:

Function getLastRow1 and getLastRow2 will return 0 for column B
Function getLastRow3 will return 1 for column B
Depend on your case, you will tweak them for your needs.
function getLastRow1(sheet, column)
var data = sheet.getRange(1, column, sheet.getLastRow()).getValues();
while(typeof data[data.length-1] !== 'undefined'
&& data[data.length-1][0].length === 0)
data.pop();
return data.length;
function test()
var sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet6');
Logger.log('Cách 1');
Logger.log("Dòng cuối cùng của cột A là: " + getLastRow1(sh, 1));
Logger.log("Dòng cuối cùng của cột B là: " + getLastRow1(sh, 2));
Logger.log("Dòng cuối cùng của cột C là: " + getLastRow1(sh, 3));
Logger.log("Dòng cuối cùng của cột D là: " + getLastRow1(sh, 4));
Logger.log("Dòng cuối cùng của cột E là: " + getLastRow1(sh, 5));
Logger.log('Cách 2');
Logger.log("Dòng cuối cùng của cột A là: " + getLastRow2(sh, 1));
Logger.log("Dòng cuối cùng của cột B là: " + getLastRow2(sh, 2));
Logger.log("Dòng cuối cùng của cột C là: " + getLastRow2(sh, 3));
Logger.log("Dòng cuối cùng của cột D là: " + getLastRow2(sh, 4));
Logger.log("Dòng cuối cùng của cột E là: " + getLastRow2(sh, 5));
Logger.log('Cách 3');
Logger.log("Dòng cuối cùng của cột A là: " + getLastRow3(sh, 'A'));
Logger.log("Dòng cuối cùng của cột B là: " + getLastRow3(sh, 'B'));
Logger.log("Dòng cuối cùng của cột C là: " + getLastRow3(sh, 'C'));
Logger.log("Dòng cuối cùng của cột D là: " + getLastRow3(sh, 'D'));
Logger.log("Dòng cuối cùng của cột E là: " + getLastRow3(sh, 'E'));
function getLastRow2(sheet, column)
var lr = sheet.getLastRow();
var data = sheet.getRange(1, column, lr).getValues();
while(lr > 0 && sheet.getRange(lr , column).isBlank())
lr--;
return lr;
function getLastRow3(sheet, column)
var lastRow = sheet.getLastRow();
var range = sheet.getRange(column + lastRow);
if (range.getValue() !== '')
return lastRow;
else
return range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
add a comment |
I've used getDataRegion
sheet.getRange(1, 1).getDataRegion(SpreadsheetApp.Dimension.ROWS).getLastRow()
Note that this relies on the data being contiguous (as per the OP's request).
add a comment |
I rewrote the getLastRow/getLastColumn functions to specify a row index or column index.
function get_used_rows(sheet, column_index)
for (var r = sheet.getLastRow(); r--; r > 0)
if (sheet.getRange(1, 1, sheet.getLastRow(), sheet.getLastColumn()).getCell(r, column_index).getValue() != "")
return r;
break;
function get_used_cols(sheet, row_index)
for (var c = sheet.getLastColumn(); c--; c > 0)
if (sheet.getRange(1, 1, sheet.getLastRow(), sheet.getLastColumn()).getCell(row_index, c).getValue() != "")
return c;
break;
add a comment |
Here's an alternative way of solving this. It uses a while loop but takes into consideration empty gaps between rows.
function getLastRow (column)
var iLastRow = ss.getActiveSheet().getMaxRows();
var aValues = ss.getActiveSheet().getRange(column + ":" + column).getValues();
var row = "";
while(row == "")
row = aValues[iLastRow-1];
iLastRow--;
return iLastRow;
Why would you start at the max row? Just start at the last row with data (in any column) and then check the desired column.
– tehhowch
Mar 21 '18 at 12:21
add a comment |
I am using getDataRange() followed by getNumRows(). The first function
Returns a Range corresponding to the dimensions in which data is present
and the second function
Returns the number of rows in this range.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ws = ss.getActiveSheet();
var lastRow = ws.getDataRange().getNumRows();
P.S I hope this works for all cases.
1
This is not an answer to op because op states that more data rows may exist in other columns.getDataRangereturns a rectangular array.
– tehhowch
Mar 30 '18 at 11:30
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f17632165%2fdetermining-the-last-row-in-a-single-column%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
15 Answers
15
active
oldest
votes
15 Answers
15
active
oldest
votes
active
oldest
votes
active
oldest
votes
How about using a JavaScript trick?
var Avals = ss.getRange("A1:A").getValues();
var Alast = Avals.filter(String).length;
I borrowed this idea from this answer. The Array.filter() method is operating on the Avals array, which contains all the cells in column A. By filtering on a native function's constructor, we get back only non-null elements.
This works for a single column only; if the range contains multiple columns,then the outcome of filter() will include cells from all columns, and thus be outside the populated dimensions of the range.
6
Very crafty. I look forward to the day when I understand javascript well enough to think as creatively as that. All in due time, I suppose. However in the meantime, I have enjoyed seeing the way you think. And kudos to you for citing the inspiration for your solution. Classy. Thanks yet again.
– 5th4x4
Jul 14 '13 at 12:56
1
Something to point out that is almost certainly obvious to more experienced coders is that the range can not span more than a single column. This was something I didn't quite get, but Mogsdad pointed this out in a comment (that was deleted) that it can't span more than a single column. Again, I just want to put this here for those that are on my experience level and still having trouble grasping some concepts. Thanks, Mogsdad.
– Soundfx4
Dec 30 '15 at 5:57
3
@5th4x4 Clarifying question from a javascript novice: wouldn't that return the number of cells in a row that were non-null, not necessarily the number of the row number of the last cell with content if there was a gap in the above cells somewhere? So something like this while loop could be used to just trim the null elements off the end of the array.
– Scotosaurus
Nov 20 '17 at 21:17
1
@Scotosaurus That's right. However, the question specifically addresses the fact that the data does not have any empty gaps: "it's all contiguous - no gaps in the data/rows", so the answer is correct but will not work on data with gaps.
– dnlmzw
Mar 21 '18 at 8:58
@Mogsdad - I do not believe cells are "null"; they're empty strings [''], at least in my experience
– Peter
Apr 27 at 19:58
|
show 1 more comment
How about using a JavaScript trick?
var Avals = ss.getRange("A1:A").getValues();
var Alast = Avals.filter(String).length;
I borrowed this idea from this answer. The Array.filter() method is operating on the Avals array, which contains all the cells in column A. By filtering on a native function's constructor, we get back only non-null elements.
This works for a single column only; if the range contains multiple columns,then the outcome of filter() will include cells from all columns, and thus be outside the populated dimensions of the range.
6
Very crafty. I look forward to the day when I understand javascript well enough to think as creatively as that. All in due time, I suppose. However in the meantime, I have enjoyed seeing the way you think. And kudos to you for citing the inspiration for your solution. Classy. Thanks yet again.
– 5th4x4
Jul 14 '13 at 12:56
1
Something to point out that is almost certainly obvious to more experienced coders is that the range can not span more than a single column. This was something I didn't quite get, but Mogsdad pointed this out in a comment (that was deleted) that it can't span more than a single column. Again, I just want to put this here for those that are on my experience level and still having trouble grasping some concepts. Thanks, Mogsdad.
– Soundfx4
Dec 30 '15 at 5:57
3
@5th4x4 Clarifying question from a javascript novice: wouldn't that return the number of cells in a row that were non-null, not necessarily the number of the row number of the last cell with content if there was a gap in the above cells somewhere? So something like this while loop could be used to just trim the null elements off the end of the array.
– Scotosaurus
Nov 20 '17 at 21:17
1
@Scotosaurus That's right. However, the question specifically addresses the fact that the data does not have any empty gaps: "it's all contiguous - no gaps in the data/rows", so the answer is correct but will not work on data with gaps.
– dnlmzw
Mar 21 '18 at 8:58
@Mogsdad - I do not believe cells are "null"; they're empty strings [''], at least in my experience
– Peter
Apr 27 at 19:58
|
show 1 more comment
How about using a JavaScript trick?
var Avals = ss.getRange("A1:A").getValues();
var Alast = Avals.filter(String).length;
I borrowed this idea from this answer. The Array.filter() method is operating on the Avals array, which contains all the cells in column A. By filtering on a native function's constructor, we get back only non-null elements.
This works for a single column only; if the range contains multiple columns,then the outcome of filter() will include cells from all columns, and thus be outside the populated dimensions of the range.
How about using a JavaScript trick?
var Avals = ss.getRange("A1:A").getValues();
var Alast = Avals.filter(String).length;
I borrowed this idea from this answer. The Array.filter() method is operating on the Avals array, which contains all the cells in column A. By filtering on a native function's constructor, we get back only non-null elements.
This works for a single column only; if the range contains multiple columns,then the outcome of filter() will include cells from all columns, and thus be outside the populated dimensions of the range.
edited Jan 13 '18 at 16:14
answered Jul 14 '13 at 6:39
MogsdadMogsdad
34.5k12 gold badges102 silver badges212 bronze badges
34.5k12 gold badges102 silver badges212 bronze badges
6
Very crafty. I look forward to the day when I understand javascript well enough to think as creatively as that. All in due time, I suppose. However in the meantime, I have enjoyed seeing the way you think. And kudos to you for citing the inspiration for your solution. Classy. Thanks yet again.
– 5th4x4
Jul 14 '13 at 12:56
1
Something to point out that is almost certainly obvious to more experienced coders is that the range can not span more than a single column. This was something I didn't quite get, but Mogsdad pointed this out in a comment (that was deleted) that it can't span more than a single column. Again, I just want to put this here for those that are on my experience level and still having trouble grasping some concepts. Thanks, Mogsdad.
– Soundfx4
Dec 30 '15 at 5:57
3
@5th4x4 Clarifying question from a javascript novice: wouldn't that return the number of cells in a row that were non-null, not necessarily the number of the row number of the last cell with content if there was a gap in the above cells somewhere? So something like this while loop could be used to just trim the null elements off the end of the array.
– Scotosaurus
Nov 20 '17 at 21:17
1
@Scotosaurus That's right. However, the question specifically addresses the fact that the data does not have any empty gaps: "it's all contiguous - no gaps in the data/rows", so the answer is correct but will not work on data with gaps.
– dnlmzw
Mar 21 '18 at 8:58
@Mogsdad - I do not believe cells are "null"; they're empty strings [''], at least in my experience
– Peter
Apr 27 at 19:58
|
show 1 more comment
6
Very crafty. I look forward to the day when I understand javascript well enough to think as creatively as that. All in due time, I suppose. However in the meantime, I have enjoyed seeing the way you think. And kudos to you for citing the inspiration for your solution. Classy. Thanks yet again.
– 5th4x4
Jul 14 '13 at 12:56
1
Something to point out that is almost certainly obvious to more experienced coders is that the range can not span more than a single column. This was something I didn't quite get, but Mogsdad pointed this out in a comment (that was deleted) that it can't span more than a single column. Again, I just want to put this here for those that are on my experience level and still having trouble grasping some concepts. Thanks, Mogsdad.
– Soundfx4
Dec 30 '15 at 5:57
3
@5th4x4 Clarifying question from a javascript novice: wouldn't that return the number of cells in a row that were non-null, not necessarily the number of the row number of the last cell with content if there was a gap in the above cells somewhere? So something like this while loop could be used to just trim the null elements off the end of the array.
– Scotosaurus
Nov 20 '17 at 21:17
1
@Scotosaurus That's right. However, the question specifically addresses the fact that the data does not have any empty gaps: "it's all contiguous - no gaps in the data/rows", so the answer is correct but will not work on data with gaps.
– dnlmzw
Mar 21 '18 at 8:58
@Mogsdad - I do not believe cells are "null"; they're empty strings [''], at least in my experience
– Peter
Apr 27 at 19:58
6
6
Very crafty. I look forward to the day when I understand javascript well enough to think as creatively as that. All in due time, I suppose. However in the meantime, I have enjoyed seeing the way you think. And kudos to you for citing the inspiration for your solution. Classy. Thanks yet again.
– 5th4x4
Jul 14 '13 at 12:56
Very crafty. I look forward to the day when I understand javascript well enough to think as creatively as that. All in due time, I suppose. However in the meantime, I have enjoyed seeing the way you think. And kudos to you for citing the inspiration for your solution. Classy. Thanks yet again.
– 5th4x4
Jul 14 '13 at 12:56
1
1
Something to point out that is almost certainly obvious to more experienced coders is that the range can not span more than a single column. This was something I didn't quite get, but Mogsdad pointed this out in a comment (that was deleted) that it can't span more than a single column. Again, I just want to put this here for those that are on my experience level and still having trouble grasping some concepts. Thanks, Mogsdad.
– Soundfx4
Dec 30 '15 at 5:57
Something to point out that is almost certainly obvious to more experienced coders is that the range can not span more than a single column. This was something I didn't quite get, but Mogsdad pointed this out in a comment (that was deleted) that it can't span more than a single column. Again, I just want to put this here for those that are on my experience level and still having trouble grasping some concepts. Thanks, Mogsdad.
– Soundfx4
Dec 30 '15 at 5:57
3
3
@5th4x4 Clarifying question from a javascript novice: wouldn't that return the number of cells in a row that were non-null, not necessarily the number of the row number of the last cell with content if there was a gap in the above cells somewhere? So something like this while loop could be used to just trim the null elements off the end of the array.
– Scotosaurus
Nov 20 '17 at 21:17
@5th4x4 Clarifying question from a javascript novice: wouldn't that return the number of cells in a row that were non-null, not necessarily the number of the row number of the last cell with content if there was a gap in the above cells somewhere? So something like this while loop could be used to just trim the null elements off the end of the array.
– Scotosaurus
Nov 20 '17 at 21:17
1
1
@Scotosaurus That's right. However, the question specifically addresses the fact that the data does not have any empty gaps: "it's all contiguous - no gaps in the data/rows", so the answer is correct but will not work on data with gaps.
– dnlmzw
Mar 21 '18 at 8:58
@Scotosaurus That's right. However, the question specifically addresses the fact that the data does not have any empty gaps: "it's all contiguous - no gaps in the data/rows", so the answer is correct but will not work on data with gaps.
– dnlmzw
Mar 21 '18 at 8:58
@Mogsdad - I do not believe cells are "null"; they're empty strings [''], at least in my experience
– Peter
Apr 27 at 19:58
@Mogsdad - I do not believe cells are "null"; they're empty strings [''], at least in my experience
– Peter
Apr 27 at 19:58
|
show 1 more comment
Although there is no straighforward formula, I can think of, it doesn't require dozens of lines of code to find out the last row in column A. Try this simple function. Use it in a cell the normal way you'd use some other function =CountColA()
function CountColA()
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
for(var i = data.length-1 ; i >=0 ; i--)
if (data[i][0] != null && data[i][0] != '')
return i+1 ;
the above returns the last row of the entire worksheet, not col A. I need ONLY the last row of col A in the form of a variable for use within the script itself. Since there is no magic pill for this, I guess I'll just loop down from A1 until I hit (empty) paydirt. Thanks anyway.
– 5th4x4
Jul 13 '13 at 18:06
1
Sorry, it was a small error from my end. Please see the corrected script.
– Srik
Jul 14 '13 at 12:14
add a comment |
Although there is no straighforward formula, I can think of, it doesn't require dozens of lines of code to find out the last row in column A. Try this simple function. Use it in a cell the normal way you'd use some other function =CountColA()
function CountColA()
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
for(var i = data.length-1 ; i >=0 ; i--)
if (data[i][0] != null && data[i][0] != '')
return i+1 ;
the above returns the last row of the entire worksheet, not col A. I need ONLY the last row of col A in the form of a variable for use within the script itself. Since there is no magic pill for this, I guess I'll just loop down from A1 until I hit (empty) paydirt. Thanks anyway.
– 5th4x4
Jul 13 '13 at 18:06
1
Sorry, it was a small error from my end. Please see the corrected script.
– Srik
Jul 14 '13 at 12:14
add a comment |
Although there is no straighforward formula, I can think of, it doesn't require dozens of lines of code to find out the last row in column A. Try this simple function. Use it in a cell the normal way you'd use some other function =CountColA()
function CountColA()
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
for(var i = data.length-1 ; i >=0 ; i--)
if (data[i][0] != null && data[i][0] != '')
return i+1 ;
Although there is no straighforward formula, I can think of, it doesn't require dozens of lines of code to find out the last row in column A. Try this simple function. Use it in a cell the normal way you'd use some other function =CountColA()
function CountColA()
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
for(var i = data.length-1 ; i >=0 ; i--)
if (data[i][0] != null && data[i][0] != '')
return i+1 ;
edited Jul 14 '13 at 12:14
answered Jul 13 '13 at 17:22
SrikSrik
7,2241 gold badge14 silver badges28 bronze badges
7,2241 gold badge14 silver badges28 bronze badges
the above returns the last row of the entire worksheet, not col A. I need ONLY the last row of col A in the form of a variable for use within the script itself. Since there is no magic pill for this, I guess I'll just loop down from A1 until I hit (empty) paydirt. Thanks anyway.
– 5th4x4
Jul 13 '13 at 18:06
1
Sorry, it was a small error from my end. Please see the corrected script.
– Srik
Jul 14 '13 at 12:14
add a comment |
the above returns the last row of the entire worksheet, not col A. I need ONLY the last row of col A in the form of a variable for use within the script itself. Since there is no magic pill for this, I guess I'll just loop down from A1 until I hit (empty) paydirt. Thanks anyway.
– 5th4x4
Jul 13 '13 at 18:06
1
Sorry, it was a small error from my end. Please see the corrected script.
– Srik
Jul 14 '13 at 12:14
the above returns the last row of the entire worksheet, not col A. I need ONLY the last row of col A in the form of a variable for use within the script itself. Since there is no magic pill for this, I guess I'll just loop down from A1 until I hit (empty) paydirt. Thanks anyway.
– 5th4x4
Jul 13 '13 at 18:06
the above returns the last row of the entire worksheet, not col A. I need ONLY the last row of col A in the form of a variable for use within the script itself. Since there is no magic pill for this, I guess I'll just loop down from A1 until I hit (empty) paydirt. Thanks anyway.
– 5th4x4
Jul 13 '13 at 18:06
1
1
Sorry, it was a small error from my end. Please see the corrected script.
– Srik
Jul 14 '13 at 12:14
Sorry, it was a small error from my end. Please see the corrected script.
– Srik
Jul 14 '13 at 12:14
add a comment |
You can do this by going in the reverse way.
Starting from the last row in spreadsheet and going up till you get some value. This will work in all the cases even if you have some empty rows in between.
Code looks like below:
var iLastRowWithData = lastValue('A');
function lastValue(column)
var iLastRow = SpreadsheetApp.getActiveSheet().getMaxRows();
var aValues = SpreadsheetApp.getActiveSheet().getRange(column + "2:" + column + lastRow).getValues();
for (; aValues[iLastRow - 1] == "" && iLastRow > 0; iLastRow--)
return iLastRow;
add a comment |
You can do this by going in the reverse way.
Starting from the last row in spreadsheet and going up till you get some value. This will work in all the cases even if you have some empty rows in between.
Code looks like below:
var iLastRowWithData = lastValue('A');
function lastValue(column)
var iLastRow = SpreadsheetApp.getActiveSheet().getMaxRows();
var aValues = SpreadsheetApp.getActiveSheet().getRange(column + "2:" + column + lastRow).getValues();
for (; aValues[iLastRow - 1] == "" && iLastRow > 0; iLastRow--)
return iLastRow;
add a comment |
You can do this by going in the reverse way.
Starting from the last row in spreadsheet and going up till you get some value. This will work in all the cases even if you have some empty rows in between.
Code looks like below:
var iLastRowWithData = lastValue('A');
function lastValue(column)
var iLastRow = SpreadsheetApp.getActiveSheet().getMaxRows();
var aValues = SpreadsheetApp.getActiveSheet().getRange(column + "2:" + column + lastRow).getValues();
for (; aValues[iLastRow - 1] == "" && iLastRow > 0; iLastRow--)
return iLastRow;
You can do this by going in the reverse way.
Starting from the last row in spreadsheet and going up till you get some value. This will work in all the cases even if you have some empty rows in between.
Code looks like below:
var iLastRowWithData = lastValue('A');
function lastValue(column)
var iLastRow = SpreadsheetApp.getActiveSheet().getMaxRows();
var aValues = SpreadsheetApp.getActiveSheet().getRange(column + "2:" + column + lastRow).getValues();
for (; aValues[iLastRow - 1] == "" && iLastRow > 0; iLastRow--)
return iLastRow;
answered Sep 1 '17 at 12:53
Akash GargAkash Garg
991 silver badge2 bronze badges
991 silver badge2 bronze badges
add a comment |
add a comment |
This will get the last row in a sheet assuming based on column A.
function getLastDataRow(sheet)
var lastRow = sheet.getLastRow();
var range = sheet.getRange("A" + lastRow);
if (range.getValue() !== "")
return lastRow;
else
return range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
This fixes @mrityunjay-pandey partially-correct answer.
To extend this answer to get the last row and column, we can use:
function columnToLetter(column)
var temp, letter = '';
while (column > 0)
temp = (column - 1) % 26;
letter = String.fromCharCode(temp + 65) + letter;
column = (column - temp - 1) / 26;
return letter;
function letterToColumn(letter)
var column = 0, length = letter.length;
for (var i = 0; i < length; i++)
column += (letter.charCodeAt(i) - 64) * Math.pow(26, length - i - 1);
return column;
function getLastDataColumn(sheet)
var lastCol = sheet.getLastColumn();
var range = sheet.getRange(columnToLetter(lastCol) + "1");
if (range.getValue() !== "")
return lastCol;
else
return range.getNextDataCell(SpreadsheetApp.Direction.PREVIOUS).getColumn();
function getLastDataRow(sheet)
var lastRow = sheet.getLastRow();
var range = sheet.getRange("A" + lastRow);
if (range.getValue() !== "")
return lastRow;
else
return range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
function run()
var sheet = SpreadsheetApp.getActiveSheet();
var [startRow, lastRow] = [2, getLastDataRow(sheet)];
var [startCol, lastCol] = [1, getLastDataColumn(sheet)];
1
nice! I like those extra functions
– Unreality
Apr 13 at 11:02
add a comment |
This will get the last row in a sheet assuming based on column A.
function getLastDataRow(sheet)
var lastRow = sheet.getLastRow();
var range = sheet.getRange("A" + lastRow);
if (range.getValue() !== "")
return lastRow;
else
return range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
This fixes @mrityunjay-pandey partially-correct answer.
To extend this answer to get the last row and column, we can use:
function columnToLetter(column)
var temp, letter = '';
while (column > 0)
temp = (column - 1) % 26;
letter = String.fromCharCode(temp + 65) + letter;
column = (column - temp - 1) / 26;
return letter;
function letterToColumn(letter)
var column = 0, length = letter.length;
for (var i = 0; i < length; i++)
column += (letter.charCodeAt(i) - 64) * Math.pow(26, length - i - 1);
return column;
function getLastDataColumn(sheet)
var lastCol = sheet.getLastColumn();
var range = sheet.getRange(columnToLetter(lastCol) + "1");
if (range.getValue() !== "")
return lastCol;
else
return range.getNextDataCell(SpreadsheetApp.Direction.PREVIOUS).getColumn();
function getLastDataRow(sheet)
var lastRow = sheet.getLastRow();
var range = sheet.getRange("A" + lastRow);
if (range.getValue() !== "")
return lastRow;
else
return range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
function run()
var sheet = SpreadsheetApp.getActiveSheet();
var [startRow, lastRow] = [2, getLastDataRow(sheet)];
var [startCol, lastCol] = [1, getLastDataColumn(sheet)];
1
nice! I like those extra functions
– Unreality
Apr 13 at 11:02
add a comment |
This will get the last row in a sheet assuming based on column A.
function getLastDataRow(sheet)
var lastRow = sheet.getLastRow();
var range = sheet.getRange("A" + lastRow);
if (range.getValue() !== "")
return lastRow;
else
return range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
This fixes @mrityunjay-pandey partially-correct answer.
To extend this answer to get the last row and column, we can use:
function columnToLetter(column)
var temp, letter = '';
while (column > 0)
temp = (column - 1) % 26;
letter = String.fromCharCode(temp + 65) + letter;
column = (column - temp - 1) / 26;
return letter;
function letterToColumn(letter)
var column = 0, length = letter.length;
for (var i = 0; i < length; i++)
column += (letter.charCodeAt(i) - 64) * Math.pow(26, length - i - 1);
return column;
function getLastDataColumn(sheet)
var lastCol = sheet.getLastColumn();
var range = sheet.getRange(columnToLetter(lastCol) + "1");
if (range.getValue() !== "")
return lastCol;
else
return range.getNextDataCell(SpreadsheetApp.Direction.PREVIOUS).getColumn();
function getLastDataRow(sheet)
var lastRow = sheet.getLastRow();
var range = sheet.getRange("A" + lastRow);
if (range.getValue() !== "")
return lastRow;
else
return range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
function run()
var sheet = SpreadsheetApp.getActiveSheet();
var [startRow, lastRow] = [2, getLastDataRow(sheet)];
var [startCol, lastCol] = [1, getLastDataColumn(sheet)];
This will get the last row in a sheet assuming based on column A.
function getLastDataRow(sheet)
var lastRow = sheet.getLastRow();
var range = sheet.getRange("A" + lastRow);
if (range.getValue() !== "")
return lastRow;
else
return range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
This fixes @mrityunjay-pandey partially-correct answer.
To extend this answer to get the last row and column, we can use:
function columnToLetter(column)
var temp, letter = '';
while (column > 0)
temp = (column - 1) % 26;
letter = String.fromCharCode(temp + 65) + letter;
column = (column - temp - 1) / 26;
return letter;
function letterToColumn(letter)
var column = 0, length = letter.length;
for (var i = 0; i < length; i++)
column += (letter.charCodeAt(i) - 64) * Math.pow(26, length - i - 1);
return column;
function getLastDataColumn(sheet)
var lastCol = sheet.getLastColumn();
var range = sheet.getRange(columnToLetter(lastCol) + "1");
if (range.getValue() !== "")
return lastCol;
else
return range.getNextDataCell(SpreadsheetApp.Direction.PREVIOUS).getColumn();
function getLastDataRow(sheet)
var lastRow = sheet.getLastRow();
var range = sheet.getRange("A" + lastRow);
if (range.getValue() !== "")
return lastRow;
else
return range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
function run()
var sheet = SpreadsheetApp.getActiveSheet();
var [startRow, lastRow] = [2, getLastDataRow(sheet)];
var [startCol, lastCol] = [1, getLastDataColumn(sheet)];
edited Dec 3 '18 at 5:01
answered Dec 3 '18 at 4:24
Al JohriAl Johri
7559 silver badges14 bronze badges
7559 silver badges14 bronze badges
1
nice! I like those extra functions
– Unreality
Apr 13 at 11:02
add a comment |
1
nice! I like those extra functions
– Unreality
Apr 13 at 11:02
1
1
nice! I like those extra functions
– Unreality
Apr 13 at 11:02
nice! I like those extra functions
– Unreality
Apr 13 at 11:02
add a comment |
For very large spreadsheets, this solution is very fast:
function GoLastRow()
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('A:AC').createFilter();
var criteria = SpreadsheetApp.newFilterCriteria().whenCellNotEmpty().build();
var rg = spreadsheet.getActiveSheet().getFilter().setColumnFilterCriteria(1, criteria).getRange();
var row = rg.getNextDataCell (SpreadsheetApp.Direction.DOWN);
LastRow = row.getRow();
spreadsheet.getActiveSheet().getFilter().remove();
spreadsheet.getActiveSheet().getRange(LastRow+1, 1).activate();
;
add a comment |
For very large spreadsheets, this solution is very fast:
function GoLastRow()
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('A:AC').createFilter();
var criteria = SpreadsheetApp.newFilterCriteria().whenCellNotEmpty().build();
var rg = spreadsheet.getActiveSheet().getFilter().setColumnFilterCriteria(1, criteria).getRange();
var row = rg.getNextDataCell (SpreadsheetApp.Direction.DOWN);
LastRow = row.getRow();
spreadsheet.getActiveSheet().getFilter().remove();
spreadsheet.getActiveSheet().getRange(LastRow+1, 1).activate();
;
add a comment |
For very large spreadsheets, this solution is very fast:
function GoLastRow()
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('A:AC').createFilter();
var criteria = SpreadsheetApp.newFilterCriteria().whenCellNotEmpty().build();
var rg = spreadsheet.getActiveSheet().getFilter().setColumnFilterCriteria(1, criteria).getRange();
var row = rg.getNextDataCell (SpreadsheetApp.Direction.DOWN);
LastRow = row.getRow();
spreadsheet.getActiveSheet().getFilter().remove();
spreadsheet.getActiveSheet().getRange(LastRow+1, 1).activate();
;
For very large spreadsheets, this solution is very fast:
function GoLastRow()
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('A:AC').createFilter();
var criteria = SpreadsheetApp.newFilterCriteria().whenCellNotEmpty().build();
var rg = spreadsheet.getActiveSheet().getFilter().setColumnFilterCriteria(1, criteria).getRange();
var row = rg.getNextDataCell (SpreadsheetApp.Direction.DOWN);
LastRow = row.getRow();
spreadsheet.getActiveSheet().getFilter().remove();
spreadsheet.getActiveSheet().getRange(LastRow+1, 1).activate();
;
answered Oct 25 '18 at 19:40
Luciano PiviLuciano Pivi
211 bronze badge
211 bronze badge
add a comment |
add a comment |
To get the number of columns or last column's index:
var numColumns = sheet.getLastColumn()
To get the no of rows or last row's index:
var numRows = sheet.getLastRow()
where
var sheet = SpreadsheetApp.getActiveSheet()
3
this looks at the entire sheet, including empty cells, which doesn't sound like it's what the OP wants.
– Ryan Tuck
Mar 29 '17 at 15:55
add a comment |
To get the number of columns or last column's index:
var numColumns = sheet.getLastColumn()
To get the no of rows or last row's index:
var numRows = sheet.getLastRow()
where
var sheet = SpreadsheetApp.getActiveSheet()
3
this looks at the entire sheet, including empty cells, which doesn't sound like it's what the OP wants.
– Ryan Tuck
Mar 29 '17 at 15:55
add a comment |
To get the number of columns or last column's index:
var numColumns = sheet.getLastColumn()
To get the no of rows or last row's index:
var numRows = sheet.getLastRow()
where
var sheet = SpreadsheetApp.getActiveSheet()
To get the number of columns or last column's index:
var numColumns = sheet.getLastColumn()
To get the no of rows or last row's index:
var numRows = sheet.getLastRow()
where
var sheet = SpreadsheetApp.getActiveSheet()
edited Apr 29 '18 at 22:15
user6655984
answered Feb 24 '17 at 22:27
Ashish VermaAshish Verma
1021 silver badge9 bronze badges
1021 silver badge9 bronze badges
3
this looks at the entire sheet, including empty cells, which doesn't sound like it's what the OP wants.
– Ryan Tuck
Mar 29 '17 at 15:55
add a comment |
3
this looks at the entire sheet, including empty cells, which doesn't sound like it's what the OP wants.
– Ryan Tuck
Mar 29 '17 at 15:55
3
3
this looks at the entire sheet, including empty cells, which doesn't sound like it's what the OP wants.
– Ryan Tuck
Mar 29 '17 at 15:55
this looks at the entire sheet, including empty cells, which doesn't sound like it's what the OP wants.
– Ryan Tuck
Mar 29 '17 at 15:55
add a comment |
This may be another way to go around lastrow.
You may need to play around with the code to suit your needs
function fill()
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('a1').activate();
var lsr = spreadsheet.getLastRow();
lsr=lsr+1;
lsr="A1:A"+lsr;
spreadsheet.getActiveRange().autoFill(spreadsheet.getRange(lsr), SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
;
add a comment |
This may be another way to go around lastrow.
You may need to play around with the code to suit your needs
function fill()
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('a1').activate();
var lsr = spreadsheet.getLastRow();
lsr=lsr+1;
lsr="A1:A"+lsr;
spreadsheet.getActiveRange().autoFill(spreadsheet.getRange(lsr), SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
;
add a comment |
This may be another way to go around lastrow.
You may need to play around with the code to suit your needs
function fill()
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('a1').activate();
var lsr = spreadsheet.getLastRow();
lsr=lsr+1;
lsr="A1:A"+lsr;
spreadsheet.getActiveRange().autoFill(spreadsheet.getRange(lsr), SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
;
This may be another way to go around lastrow.
You may need to play around with the code to suit your needs
function fill()
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('a1').activate();
var lsr = spreadsheet.getLastRow();
lsr=lsr+1;
lsr="A1:A"+lsr;
spreadsheet.getActiveRange().autoFill(spreadsheet.getRange(lsr), SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
;
answered May 22 '18 at 2:11
Tariq KhalafTariq Khalaf
641 gold badge1 silver badge10 bronze badges
641 gold badge1 silver badge10 bronze badges
add a comment |
add a comment |
var Direction=SpreadsheetApp.Direction;
var aLast =ss.getRange("A"+(ss.getLastRow()+1)).getNextDataCell(Direction.UP).getRow();
Please don't just post code - add an explanation as well.
– CertainPerformance
Jul 23 '18 at 7:32
add a comment |
var Direction=SpreadsheetApp.Direction;
var aLast =ss.getRange("A"+(ss.getLastRow()+1)).getNextDataCell(Direction.UP).getRow();
Please don't just post code - add an explanation as well.
– CertainPerformance
Jul 23 '18 at 7:32
add a comment |
var Direction=SpreadsheetApp.Direction;
var aLast =ss.getRange("A"+(ss.getLastRow()+1)).getNextDataCell(Direction.UP).getRow();
var Direction=SpreadsheetApp.Direction;
var aLast =ss.getRange("A"+(ss.getLastRow()+1)).getNextDataCell(Direction.UP).getRow();
answered Jul 23 '18 at 7:12
Mrityunjay pandeyMrityunjay pandey
194 bronze badges
194 bronze badges
Please don't just post code - add an explanation as well.
– CertainPerformance
Jul 23 '18 at 7:32
add a comment |
Please don't just post code - add an explanation as well.
– CertainPerformance
Jul 23 '18 at 7:32
Please don't just post code - add an explanation as well.
– CertainPerformance
Jul 23 '18 at 7:32
Please don't just post code - add an explanation as well.
– CertainPerformance
Jul 23 '18 at 7:32
add a comment |
personally I had a similar issue and went with something like this:
function getLastRowinColumn (ws, column)
var page_lastrow = ws.getDataRange().getNumRows();
var last_row_col = 0
for (i=1; i<=page_lastrow;i++)
if (!(spread.getRange(column.concat("",i)).isBlank())) last_row_col = i;
return last_row_col
It looks for the number of rows in the ws and loops through each cell in your column. When it finds a non-empty cell it updates the position of that cell in the last_row_col variable. It has the advantage of allowing you to have non-contiguous columns and still know the last row (assuming you are going through the whole column).
add a comment |
personally I had a similar issue and went with something like this:
function getLastRowinColumn (ws, column)
var page_lastrow = ws.getDataRange().getNumRows();
var last_row_col = 0
for (i=1; i<=page_lastrow;i++)
if (!(spread.getRange(column.concat("",i)).isBlank())) last_row_col = i;
return last_row_col
It looks for the number of rows in the ws and loops through each cell in your column. When it finds a non-empty cell it updates the position of that cell in the last_row_col variable. It has the advantage of allowing you to have non-contiguous columns and still know the last row (assuming you are going through the whole column).
add a comment |
personally I had a similar issue and went with something like this:
function getLastRowinColumn (ws, column)
var page_lastrow = ws.getDataRange().getNumRows();
var last_row_col = 0
for (i=1; i<=page_lastrow;i++)
if (!(spread.getRange(column.concat("",i)).isBlank())) last_row_col = i;
return last_row_col
It looks for the number of rows in the ws and loops through each cell in your column. When it finds a non-empty cell it updates the position of that cell in the last_row_col variable. It has the advantage of allowing you to have non-contiguous columns and still know the last row (assuming you are going through the whole column).
personally I had a similar issue and went with something like this:
function getLastRowinColumn (ws, column)
var page_lastrow = ws.getDataRange().getNumRows();
var last_row_col = 0
for (i=1; i<=page_lastrow;i++)
if (!(spread.getRange(column.concat("",i)).isBlank())) last_row_col = i;
return last_row_col
It looks for the number of rows in the ws and loops through each cell in your column. When it finds a non-empty cell it updates the position of that cell in the last_row_col variable. It has the advantage of allowing you to have non-contiguous columns and still know the last row (assuming you are going through the whole column).
answered Mar 13 at 2:31
jello195jello195
214 bronze badges
214 bronze badges
add a comment |
add a comment |
Never too late to post an alternative answer I hope. Here's a snippet of my Find last Cell. I'm primarily interested in speed. On a DB I'm using with around 150,000 rows this function took (average) 0.087 seconds to find solution compared to @Mogsdad elegant JS solution above which takes (average) 0.53 sec on same data. Both arrays were pre-loaded before the function call. It makes use of recursion to do a binary search. For 100,000+ rows you should find it takes no more than 15 to 20 hops to return it's result.
I've left the Log calls in so you can test it in the console first and see its workings.
/* @OnlyCurrentDoc */
function myLastRow()
var ss=SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var colArray = ss.getRange('A1:A').getDisplayValues(); // Change to relevant column label and put in Cache
var TestRow=ss.getLastRow();
var MaxRow=ss.getMaxRows();
Logger.log ('TestRow = %s',TestRow);
Logger.log ('MaxRow = %s',MaxRow);
var FoundRow=FindLastRow(TestRow,MaxRow);
Logger.log ('FoundRow = %s',FoundRow);
function FindLastRow(v_TestRow,v_MaxRow)
/* Some housekeeping/error trapping first
* 1) Check that LastRow doesn't = Max Rows. If so then suggest to add a few lines as this
* indicates the LastRow was the end of the sheet.
* 2) Check it's not a new sheet with no data ie, LastRow = 0 and/or cell A1 is empty.
* 3) A return result of 0 = an error otherwise any positive value is a valid result.
*/
return !(colArray[0][0]) ? 1 // if first row is empty then presume it's a new empty sheet
:!!(colArray[v_TestRow][0]) ? v_TestRow // if the last row is not empty then column A was the longest
: v_MaxRow==v_TestRow ? v_TestRow // if Last=Max then consider adding a line here to extend row count, else
: searchPair(0,v_TestRow); // get on an find the last row
function searchPair(LowRow,HighRow)(!!(colArray[BinRow][0])) ? searchPair(BinRow+1,HighRow)
: false; // Error
/* The premise for the above logic is that the binary search is looking for a specific pairing, <Text/No text>
* on adjacent rows. You said there are no gaps so the pairing <No Text/Text> is not tested as it's irrelevant.
* If the logic finds <No Text/No Text> then it looks back up the sheet, if it finds <Text/Text> it looks further
* down the sheet. I think you'll find this is quite fast, especially on datasets > 100,000 rows.
*/
add a comment |
Never too late to post an alternative answer I hope. Here's a snippet of my Find last Cell. I'm primarily interested in speed. On a DB I'm using with around 150,000 rows this function took (average) 0.087 seconds to find solution compared to @Mogsdad elegant JS solution above which takes (average) 0.53 sec on same data. Both arrays were pre-loaded before the function call. It makes use of recursion to do a binary search. For 100,000+ rows you should find it takes no more than 15 to 20 hops to return it's result.
I've left the Log calls in so you can test it in the console first and see its workings.
/* @OnlyCurrentDoc */
function myLastRow()
var ss=SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var colArray = ss.getRange('A1:A').getDisplayValues(); // Change to relevant column label and put in Cache
var TestRow=ss.getLastRow();
var MaxRow=ss.getMaxRows();
Logger.log ('TestRow = %s',TestRow);
Logger.log ('MaxRow = %s',MaxRow);
var FoundRow=FindLastRow(TestRow,MaxRow);
Logger.log ('FoundRow = %s',FoundRow);
function FindLastRow(v_TestRow,v_MaxRow)
/* Some housekeeping/error trapping first
* 1) Check that LastRow doesn't = Max Rows. If so then suggest to add a few lines as this
* indicates the LastRow was the end of the sheet.
* 2) Check it's not a new sheet with no data ie, LastRow = 0 and/or cell A1 is empty.
* 3) A return result of 0 = an error otherwise any positive value is a valid result.
*/
return !(colArray[0][0]) ? 1 // if first row is empty then presume it's a new empty sheet
:!!(colArray[v_TestRow][0]) ? v_TestRow // if the last row is not empty then column A was the longest
: v_MaxRow==v_TestRow ? v_TestRow // if Last=Max then consider adding a line here to extend row count, else
: searchPair(0,v_TestRow); // get on an find the last row
function searchPair(LowRow,HighRow)(!!(colArray[BinRow][0])) ? searchPair(BinRow+1,HighRow)
: false; // Error
/* The premise for the above logic is that the binary search is looking for a specific pairing, <Text/No text>
* on adjacent rows. You said there are no gaps so the pairing <No Text/Text> is not tested as it's irrelevant.
* If the logic finds <No Text/No Text> then it looks back up the sheet, if it finds <Text/Text> it looks further
* down the sheet. I think you'll find this is quite fast, especially on datasets > 100,000 rows.
*/
add a comment |
Never too late to post an alternative answer I hope. Here's a snippet of my Find last Cell. I'm primarily interested in speed. On a DB I'm using with around 150,000 rows this function took (average) 0.087 seconds to find solution compared to @Mogsdad elegant JS solution above which takes (average) 0.53 sec on same data. Both arrays were pre-loaded before the function call. It makes use of recursion to do a binary search. For 100,000+ rows you should find it takes no more than 15 to 20 hops to return it's result.
I've left the Log calls in so you can test it in the console first and see its workings.
/* @OnlyCurrentDoc */
function myLastRow()
var ss=SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var colArray = ss.getRange('A1:A').getDisplayValues(); // Change to relevant column label and put in Cache
var TestRow=ss.getLastRow();
var MaxRow=ss.getMaxRows();
Logger.log ('TestRow = %s',TestRow);
Logger.log ('MaxRow = %s',MaxRow);
var FoundRow=FindLastRow(TestRow,MaxRow);
Logger.log ('FoundRow = %s',FoundRow);
function FindLastRow(v_TestRow,v_MaxRow)
/* Some housekeeping/error trapping first
* 1) Check that LastRow doesn't = Max Rows. If so then suggest to add a few lines as this
* indicates the LastRow was the end of the sheet.
* 2) Check it's not a new sheet with no data ie, LastRow = 0 and/or cell A1 is empty.
* 3) A return result of 0 = an error otherwise any positive value is a valid result.
*/
return !(colArray[0][0]) ? 1 // if first row is empty then presume it's a new empty sheet
:!!(colArray[v_TestRow][0]) ? v_TestRow // if the last row is not empty then column A was the longest
: v_MaxRow==v_TestRow ? v_TestRow // if Last=Max then consider adding a line here to extend row count, else
: searchPair(0,v_TestRow); // get on an find the last row
function searchPair(LowRow,HighRow)(!!(colArray[BinRow][0])) ? searchPair(BinRow+1,HighRow)
: false; // Error
/* The premise for the above logic is that the binary search is looking for a specific pairing, <Text/No text>
* on adjacent rows. You said there are no gaps so the pairing <No Text/Text> is not tested as it's irrelevant.
* If the logic finds <No Text/No Text> then it looks back up the sheet, if it finds <Text/Text> it looks further
* down the sheet. I think you'll find this is quite fast, especially on datasets > 100,000 rows.
*/
Never too late to post an alternative answer I hope. Here's a snippet of my Find last Cell. I'm primarily interested in speed. On a DB I'm using with around 150,000 rows this function took (average) 0.087 seconds to find solution compared to @Mogsdad elegant JS solution above which takes (average) 0.53 sec on same data. Both arrays were pre-loaded before the function call. It makes use of recursion to do a binary search. For 100,000+ rows you should find it takes no more than 15 to 20 hops to return it's result.
I've left the Log calls in so you can test it in the console first and see its workings.
/* @OnlyCurrentDoc */
function myLastRow()
var ss=SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var colArray = ss.getRange('A1:A').getDisplayValues(); // Change to relevant column label and put in Cache
var TestRow=ss.getLastRow();
var MaxRow=ss.getMaxRows();
Logger.log ('TestRow = %s',TestRow);
Logger.log ('MaxRow = %s',MaxRow);
var FoundRow=FindLastRow(TestRow,MaxRow);
Logger.log ('FoundRow = %s',FoundRow);
function FindLastRow(v_TestRow,v_MaxRow)
/* Some housekeeping/error trapping first
* 1) Check that LastRow doesn't = Max Rows. If so then suggest to add a few lines as this
* indicates the LastRow was the end of the sheet.
* 2) Check it's not a new sheet with no data ie, LastRow = 0 and/or cell A1 is empty.
* 3) A return result of 0 = an error otherwise any positive value is a valid result.
*/
return !(colArray[0][0]) ? 1 // if first row is empty then presume it's a new empty sheet
:!!(colArray[v_TestRow][0]) ? v_TestRow // if the last row is not empty then column A was the longest
: v_MaxRow==v_TestRow ? v_TestRow // if Last=Max then consider adding a line here to extend row count, else
: searchPair(0,v_TestRow); // get on an find the last row
function searchPair(LowRow,HighRow)(!!(colArray[BinRow][0])) ? searchPair(BinRow+1,HighRow)
: false; // Error
/* The premise for the above logic is that the binary search is looking for a specific pairing, <Text/No text>
* on adjacent rows. You said there are no gaps so the pairing <No Text/Text> is not tested as it's irrelevant.
* If the logic finds <No Text/No Text> then it looks back up the sheet, if it finds <Text/Text> it looks further
* down the sheet. I think you'll find this is quite fast, especially on datasets > 100,000 rows.
*/
edited Apr 17 at 0:52
answered Apr 2 at 5:05
DeeKay789DeeKay789
311 silver badge6 bronze badges
311 silver badge6 bronze badges
add a comment |
add a comment |
I tried to write up 3 following functions, you can test them for different cases of yours. This is the data I tested with:

Function getLastRow1 and getLastRow2 will return 0 for column B
Function getLastRow3 will return 1 for column B
Depend on your case, you will tweak them for your needs.
function getLastRow1(sheet, column)
var data = sheet.getRange(1, column, sheet.getLastRow()).getValues();
while(typeof data[data.length-1] !== 'undefined'
&& data[data.length-1][0].length === 0)
data.pop();
return data.length;
function test()
var sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet6');
Logger.log('Cách 1');
Logger.log("Dòng cuối cùng của cột A là: " + getLastRow1(sh, 1));
Logger.log("Dòng cuối cùng của cột B là: " + getLastRow1(sh, 2));
Logger.log("Dòng cuối cùng của cột C là: " + getLastRow1(sh, 3));
Logger.log("Dòng cuối cùng của cột D là: " + getLastRow1(sh, 4));
Logger.log("Dòng cuối cùng của cột E là: " + getLastRow1(sh, 5));
Logger.log('Cách 2');
Logger.log("Dòng cuối cùng của cột A là: " + getLastRow2(sh, 1));
Logger.log("Dòng cuối cùng của cột B là: " + getLastRow2(sh, 2));
Logger.log("Dòng cuối cùng của cột C là: " + getLastRow2(sh, 3));
Logger.log("Dòng cuối cùng của cột D là: " + getLastRow2(sh, 4));
Logger.log("Dòng cuối cùng của cột E là: " + getLastRow2(sh, 5));
Logger.log('Cách 3');
Logger.log("Dòng cuối cùng của cột A là: " + getLastRow3(sh, 'A'));
Logger.log("Dòng cuối cùng của cột B là: " + getLastRow3(sh, 'B'));
Logger.log("Dòng cuối cùng của cột C là: " + getLastRow3(sh, 'C'));
Logger.log("Dòng cuối cùng của cột D là: " + getLastRow3(sh, 'D'));
Logger.log("Dòng cuối cùng của cột E là: " + getLastRow3(sh, 'E'));
function getLastRow2(sheet, column)
var lr = sheet.getLastRow();
var data = sheet.getRange(1, column, lr).getValues();
while(lr > 0 && sheet.getRange(lr , column).isBlank())
lr--;
return lr;
function getLastRow3(sheet, column)
var lastRow = sheet.getLastRow();
var range = sheet.getRange(column + lastRow);
if (range.getValue() !== '')
return lastRow;
else
return range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
add a comment |
I tried to write up 3 following functions, you can test them for different cases of yours. This is the data I tested with:

Function getLastRow1 and getLastRow2 will return 0 for column B
Function getLastRow3 will return 1 for column B
Depend on your case, you will tweak them for your needs.
function getLastRow1(sheet, column)
var data = sheet.getRange(1, column, sheet.getLastRow()).getValues();
while(typeof data[data.length-1] !== 'undefined'
&& data[data.length-1][0].length === 0)
data.pop();
return data.length;
function test()
var sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet6');
Logger.log('Cách 1');
Logger.log("Dòng cuối cùng của cột A là: " + getLastRow1(sh, 1));
Logger.log("Dòng cuối cùng của cột B là: " + getLastRow1(sh, 2));
Logger.log("Dòng cuối cùng của cột C là: " + getLastRow1(sh, 3));
Logger.log("Dòng cuối cùng của cột D là: " + getLastRow1(sh, 4));
Logger.log("Dòng cuối cùng của cột E là: " + getLastRow1(sh, 5));
Logger.log('Cách 2');
Logger.log("Dòng cuối cùng của cột A là: " + getLastRow2(sh, 1));
Logger.log("Dòng cuối cùng của cột B là: " + getLastRow2(sh, 2));
Logger.log("Dòng cuối cùng của cột C là: " + getLastRow2(sh, 3));
Logger.log("Dòng cuối cùng của cột D là: " + getLastRow2(sh, 4));
Logger.log("Dòng cuối cùng của cột E là: " + getLastRow2(sh, 5));
Logger.log('Cách 3');
Logger.log("Dòng cuối cùng của cột A là: " + getLastRow3(sh, 'A'));
Logger.log("Dòng cuối cùng của cột B là: " + getLastRow3(sh, 'B'));
Logger.log("Dòng cuối cùng của cột C là: " + getLastRow3(sh, 'C'));
Logger.log("Dòng cuối cùng của cột D là: " + getLastRow3(sh, 'D'));
Logger.log("Dòng cuối cùng của cột E là: " + getLastRow3(sh, 'E'));
function getLastRow2(sheet, column)
var lr = sheet.getLastRow();
var data = sheet.getRange(1, column, lr).getValues();
while(lr > 0 && sheet.getRange(lr , column).isBlank())
lr--;
return lr;
function getLastRow3(sheet, column)
var lastRow = sheet.getLastRow();
var range = sheet.getRange(column + lastRow);
if (range.getValue() !== '')
return lastRow;
else
return range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
add a comment |
I tried to write up 3 following functions, you can test them for different cases of yours. This is the data I tested with:

Function getLastRow1 and getLastRow2 will return 0 for column B
Function getLastRow3 will return 1 for column B
Depend on your case, you will tweak them for your needs.
function getLastRow1(sheet, column)
var data = sheet.getRange(1, column, sheet.getLastRow()).getValues();
while(typeof data[data.length-1] !== 'undefined'
&& data[data.length-1][0].length === 0)
data.pop();
return data.length;
function test()
var sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet6');
Logger.log('Cách 1');
Logger.log("Dòng cuối cùng của cột A là: " + getLastRow1(sh, 1));
Logger.log("Dòng cuối cùng của cột B là: " + getLastRow1(sh, 2));
Logger.log("Dòng cuối cùng của cột C là: " + getLastRow1(sh, 3));
Logger.log("Dòng cuối cùng của cột D là: " + getLastRow1(sh, 4));
Logger.log("Dòng cuối cùng của cột E là: " + getLastRow1(sh, 5));
Logger.log('Cách 2');
Logger.log("Dòng cuối cùng của cột A là: " + getLastRow2(sh, 1));
Logger.log("Dòng cuối cùng của cột B là: " + getLastRow2(sh, 2));
Logger.log("Dòng cuối cùng của cột C là: " + getLastRow2(sh, 3));
Logger.log("Dòng cuối cùng của cột D là: " + getLastRow2(sh, 4));
Logger.log("Dòng cuối cùng của cột E là: " + getLastRow2(sh, 5));
Logger.log('Cách 3');
Logger.log("Dòng cuối cùng của cột A là: " + getLastRow3(sh, 'A'));
Logger.log("Dòng cuối cùng của cột B là: " + getLastRow3(sh, 'B'));
Logger.log("Dòng cuối cùng của cột C là: " + getLastRow3(sh, 'C'));
Logger.log("Dòng cuối cùng của cột D là: " + getLastRow3(sh, 'D'));
Logger.log("Dòng cuối cùng của cột E là: " + getLastRow3(sh, 'E'));
function getLastRow2(sheet, column)
var lr = sheet.getLastRow();
var data = sheet.getRange(1, column, lr).getValues();
while(lr > 0 && sheet.getRange(lr , column).isBlank())
lr--;
return lr;
function getLastRow3(sheet, column)
var lastRow = sheet.getLastRow();
var range = sheet.getRange(column + lastRow);
if (range.getValue() !== '')
return lastRow;
else
return range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
I tried to write up 3 following functions, you can test them for different cases of yours. This is the data I tested with:

Function getLastRow1 and getLastRow2 will return 0 for column B
Function getLastRow3 will return 1 for column B
Depend on your case, you will tweak them for your needs.
function getLastRow1(sheet, column)
var data = sheet.getRange(1, column, sheet.getLastRow()).getValues();
while(typeof data[data.length-1] !== 'undefined'
&& data[data.length-1][0].length === 0)
data.pop();
return data.length;
function test()
var sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet6');
Logger.log('Cách 1');
Logger.log("Dòng cuối cùng của cột A là: " + getLastRow1(sh, 1));
Logger.log("Dòng cuối cùng của cột B là: " + getLastRow1(sh, 2));
Logger.log("Dòng cuối cùng của cột C là: " + getLastRow1(sh, 3));
Logger.log("Dòng cuối cùng của cột D là: " + getLastRow1(sh, 4));
Logger.log("Dòng cuối cùng của cột E là: " + getLastRow1(sh, 5));
Logger.log('Cách 2');
Logger.log("Dòng cuối cùng của cột A là: " + getLastRow2(sh, 1));
Logger.log("Dòng cuối cùng của cột B là: " + getLastRow2(sh, 2));
Logger.log("Dòng cuối cùng của cột C là: " + getLastRow2(sh, 3));
Logger.log("Dòng cuối cùng của cột D là: " + getLastRow2(sh, 4));
Logger.log("Dòng cuối cùng của cột E là: " + getLastRow2(sh, 5));
Logger.log('Cách 3');
Logger.log("Dòng cuối cùng của cột A là: " + getLastRow3(sh, 'A'));
Logger.log("Dòng cuối cùng của cột B là: " + getLastRow3(sh, 'B'));
Logger.log("Dòng cuối cùng của cột C là: " + getLastRow3(sh, 'C'));
Logger.log("Dòng cuối cùng của cột D là: " + getLastRow3(sh, 'D'));
Logger.log("Dòng cuối cùng của cột E là: " + getLastRow3(sh, 'E'));
function getLastRow2(sheet, column)
var lr = sheet.getLastRow();
var data = sheet.getRange(1, column, lr).getValues();
while(lr > 0 && sheet.getRange(lr , column).isBlank())
lr--;
return lr;
function getLastRow3(sheet, column)
var lastRow = sheet.getLastRow();
var range = sheet.getRange(column + lastRow);
if (range.getValue() !== '')
return lastRow;
else
return range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
answered May 9 at 21:21
Đức Thanh NguyễnĐức Thanh Nguyễn
6,9891 gold badge10 silver badges17 bronze badges
6,9891 gold badge10 silver badges17 bronze badges
add a comment |
add a comment |
I've used getDataRegion
sheet.getRange(1, 1).getDataRegion(SpreadsheetApp.Dimension.ROWS).getLastRow()
Note that this relies on the data being contiguous (as per the OP's request).
add a comment |
I've used getDataRegion
sheet.getRange(1, 1).getDataRegion(SpreadsheetApp.Dimension.ROWS).getLastRow()
Note that this relies on the data being contiguous (as per the OP's request).
add a comment |
I've used getDataRegion
sheet.getRange(1, 1).getDataRegion(SpreadsheetApp.Dimension.ROWS).getLastRow()
Note that this relies on the data being contiguous (as per the OP's request).
I've used getDataRegion
sheet.getRange(1, 1).getDataRegion(SpreadsheetApp.Dimension.ROWS).getLastRow()
Note that this relies on the data being contiguous (as per the OP's request).
answered May 10 at 15:40
Simon BirtSimon Birt
1
1
add a comment |
add a comment |
I rewrote the getLastRow/getLastColumn functions to specify a row index or column index.
function get_used_rows(sheet, column_index)
for (var r = sheet.getLastRow(); r--; r > 0)
if (sheet.getRange(1, 1, sheet.getLastRow(), sheet.getLastColumn()).getCell(r, column_index).getValue() != "")
return r;
break;
function get_used_cols(sheet, row_index)
for (var c = sheet.getLastColumn(); c--; c > 0)
if (sheet.getRange(1, 1, sheet.getLastRow(), sheet.getLastColumn()).getCell(row_index, c).getValue() != "")
return c;
break;
add a comment |
I rewrote the getLastRow/getLastColumn functions to specify a row index or column index.
function get_used_rows(sheet, column_index)
for (var r = sheet.getLastRow(); r--; r > 0)
if (sheet.getRange(1, 1, sheet.getLastRow(), sheet.getLastColumn()).getCell(r, column_index).getValue() != "")
return r;
break;
function get_used_cols(sheet, row_index)
for (var c = sheet.getLastColumn(); c--; c > 0)
if (sheet.getRange(1, 1, sheet.getLastRow(), sheet.getLastColumn()).getCell(row_index, c).getValue() != "")
return c;
break;
add a comment |
I rewrote the getLastRow/getLastColumn functions to specify a row index or column index.
function get_used_rows(sheet, column_index)
for (var r = sheet.getLastRow(); r--; r > 0)
if (sheet.getRange(1, 1, sheet.getLastRow(), sheet.getLastColumn()).getCell(r, column_index).getValue() != "")
return r;
break;
function get_used_cols(sheet, row_index)
for (var c = sheet.getLastColumn(); c--; c > 0)
if (sheet.getRange(1, 1, sheet.getLastRow(), sheet.getLastColumn()).getCell(row_index, c).getValue() != "")
return c;
break;
I rewrote the getLastRow/getLastColumn functions to specify a row index or column index.
function get_used_rows(sheet, column_index)
for (var r = sheet.getLastRow(); r--; r > 0)
if (sheet.getRange(1, 1, sheet.getLastRow(), sheet.getLastColumn()).getCell(r, column_index).getValue() != "")
return r;
break;
function get_used_cols(sheet, row_index)
for (var c = sheet.getLastColumn(); c--; c > 0)
if (sheet.getRange(1, 1, sheet.getLastRow(), sheet.getLastColumn()).getCell(row_index, c).getValue() != "")
return c;
break;
answered Aug 4 '17 at 3:07
Ashton FeiAshton Fei
11 bronze badge
11 bronze badge
add a comment |
add a comment |
Here's an alternative way of solving this. It uses a while loop but takes into consideration empty gaps between rows.
function getLastRow (column)
var iLastRow = ss.getActiveSheet().getMaxRows();
var aValues = ss.getActiveSheet().getRange(column + ":" + column).getValues();
var row = "";
while(row == "")
row = aValues[iLastRow-1];
iLastRow--;
return iLastRow;
Why would you start at the max row? Just start at the last row with data (in any column) and then check the desired column.
– tehhowch
Mar 21 '18 at 12:21
add a comment |
Here's an alternative way of solving this. It uses a while loop but takes into consideration empty gaps between rows.
function getLastRow (column)
var iLastRow = ss.getActiveSheet().getMaxRows();
var aValues = ss.getActiveSheet().getRange(column + ":" + column).getValues();
var row = "";
while(row == "")
row = aValues[iLastRow-1];
iLastRow--;
return iLastRow;
Why would you start at the max row? Just start at the last row with data (in any column) and then check the desired column.
– tehhowch
Mar 21 '18 at 12:21
add a comment |
Here's an alternative way of solving this. It uses a while loop but takes into consideration empty gaps between rows.
function getLastRow (column)
var iLastRow = ss.getActiveSheet().getMaxRows();
var aValues = ss.getActiveSheet().getRange(column + ":" + column).getValues();
var row = "";
while(row == "")
row = aValues[iLastRow-1];
iLastRow--;
return iLastRow;
Here's an alternative way of solving this. It uses a while loop but takes into consideration empty gaps between rows.
function getLastRow (column)
var iLastRow = ss.getActiveSheet().getMaxRows();
var aValues = ss.getActiveSheet().getRange(column + ":" + column).getValues();
var row = "";
while(row == "")
row = aValues[iLastRow-1];
iLastRow--;
return iLastRow;
edited Mar 21 '18 at 9:30
answered Mar 21 '18 at 9:24
dnlmzwdnlmzw
4041 gold badge6 silver badges18 bronze badges
4041 gold badge6 silver badges18 bronze badges
Why would you start at the max row? Just start at the last row with data (in any column) and then check the desired column.
– tehhowch
Mar 21 '18 at 12:21
add a comment |
Why would you start at the max row? Just start at the last row with data (in any column) and then check the desired column.
– tehhowch
Mar 21 '18 at 12:21
Why would you start at the max row? Just start at the last row with data (in any column) and then check the desired column.
– tehhowch
Mar 21 '18 at 12:21
Why would you start at the max row? Just start at the last row with data (in any column) and then check the desired column.
– tehhowch
Mar 21 '18 at 12:21
add a comment |
I am using getDataRange() followed by getNumRows(). The first function
Returns a Range corresponding to the dimensions in which data is present
and the second function
Returns the number of rows in this range.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ws = ss.getActiveSheet();
var lastRow = ws.getDataRange().getNumRows();
P.S I hope this works for all cases.
1
This is not an answer to op because op states that more data rows may exist in other columns.getDataRangereturns a rectangular array.
– tehhowch
Mar 30 '18 at 11:30
add a comment |
I am using getDataRange() followed by getNumRows(). The first function
Returns a Range corresponding to the dimensions in which data is present
and the second function
Returns the number of rows in this range.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ws = ss.getActiveSheet();
var lastRow = ws.getDataRange().getNumRows();
P.S I hope this works for all cases.
1
This is not an answer to op because op states that more data rows may exist in other columns.getDataRangereturns a rectangular array.
– tehhowch
Mar 30 '18 at 11:30
add a comment |
I am using getDataRange() followed by getNumRows(). The first function
Returns a Range corresponding to the dimensions in which data is present
and the second function
Returns the number of rows in this range.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ws = ss.getActiveSheet();
var lastRow = ws.getDataRange().getNumRows();
P.S I hope this works for all cases.
I am using getDataRange() followed by getNumRows(). The first function
Returns a Range corresponding to the dimensions in which data is present
and the second function
Returns the number of rows in this range.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ws = ss.getActiveSheet();
var lastRow = ws.getDataRange().getNumRows();
P.S I hope this works for all cases.
answered Mar 30 '18 at 7:16
urwaCFCurwaCFC
4411 gold badge9 silver badges31 bronze badges
4411 gold badge9 silver badges31 bronze badges
1
This is not an answer to op because op states that more data rows may exist in other columns.getDataRangereturns a rectangular array.
– tehhowch
Mar 30 '18 at 11:30
add a comment |
1
This is not an answer to op because op states that more data rows may exist in other columns.getDataRangereturns a rectangular array.
– tehhowch
Mar 30 '18 at 11:30
1
1
This is not an answer to op because op states that more data rows may exist in other columns.
getDataRange returns a rectangular array.– tehhowch
Mar 30 '18 at 11:30
This is not an answer to op because op states that more data rows may exist in other columns.
getDataRange returns a rectangular array.– tehhowch
Mar 30 '18 at 11:30
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f17632165%2fdetermining-the-last-row-in-a-single-column%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown