Amount of rows in sheet

亡梦爱人 提交于 2020-01-22 13:38:02

问题


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?


回答1:


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




回答2:


You can also try:

i = Sheets("SheetName").UsedRange.Rows.Count

However, this can get a little buggy if you start deleting and clearing rows.

A better way to do this is:

i = Cells(Sheets("SheetName").Rows.Count, 1).End(xlup).Row

This assumes that each row has data in column 1.



来源:https://stackoverflow.com/questions/11595816/amount-of-rows-in-sheet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!