Amount of rows in sheet

前端 未结 2 560
情歌与酒
情歌与酒 2021-02-07 11:58

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?

相关标签:
2条回答
  • 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

    0 讨论(0)
  • 2021-02-07 12:47

    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.

    0 讨论(0)
提交回复
热议问题