Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Amount of rows in sheet

Tags:

excel

vba

Goal:
A variable should contain amount of rows from a specific sheet.

Problem:
What syntax code in Excel VBA do I need to count amount of rows from sheet?

like image 743
What'sUP Avatar asked Jul 21 '12 21:07

What'sUP


People also ask

How do I count the number of rows in a sheet?

Select a blank cell and type the =COUNTA function including the range of cells that you want to count. For example, we used =COUNTA(A2:A11). Just hit enter, and the COUNTA function will automatically count the cells that are not blank. You now have the total number of cells that have values in it!

What is the formula to count rows?

The most basic formula used is =ROWS(rng). The function counted the number of rows and returned a numerical value as the result.

Does Google sheets have a row limit?

You can still add up to five million rows at once, however, and if your sheet has more than two columns, you may need to do a bit of math to see how many rows you can add before reaching the barrier (10,000,000 divided by number of columns, rounded down).


1 Answers

Using the usedrange method is one of my favourites but it needs to be treated with care. It has a few flaws/gotchas. It is a known problem that excel does not keep track of the used range very well. Any reference to the used range via VBA will reset the value to the current used range. So try running this sub procedure when you are getting the used range:

Dim lRowCount as Long

Application.ActiveSheet.UsedRange
lRowCount = Worksheets("MySheet").UsedRange.Rows.Count

But be aware this will give you the used range count, so if you have blank rows at the top of your workbook (which often people do to leave space for things like filter criteria etc) then they will not be counted. The usedrange method can also be affected by formatting.

If you want the last row used, which is what I think you want, then you can use the find method which is more reliable:

Dim rLastCell As Range
Dim lLastRow  As Long

Set rLastCell = ActiveSheet.Cells.Find(What:="*", After:=.Cells(1, 1), LookIn:=xlFormulas, LookAt:= _
xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False)

If Not rLastCell Is Nothing Then lLastRow = rLastCell.Row

If you know that you have atleast one cell with data in it, then you can simplify the above to:

Dim lLastRow  As Long

lLastRow = ActiveSheet.Cells.Find(What:="*", After:=.Cells(1, 1), LookIn:=xlFormulas, LookAt:= _
xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False).Row

See here regarding used range I spoke about above

like image 138
Reafidy Avatar answered Sep 20 '22 07:09

Reafidy