Rows.count incorrect

2019-08-21 07:36发布

I have: N = Cells(Rows.Count, "B").End(xlUp).Row and it returns 1 all the time, when I have a dataset which contains 200k+ rows.

Very odd, as it is only with this workbook, as with another workbook this line works.

Questions:

Any suggestions as to why this occurs? Any possible work around? My current work around is:

Sub Macro2()

    Range("B1").Select
    Selection.End(xlDown).Select
    Selection.End(xlDown).Select
    Selection.End(xlUp).Select
    n = ActiveCell.Row
End Sub

2条回答
来,给爷笑一个
2楼-- · 2019-08-21 08:06

I am assuming that you want the code to run in active (selected) sheet. Example:

Option Explicit
Sub LastrowExample()
'declare variable lastrow as Long
Dim lastrow As Long
'get lastrow:
lastrow = Cells(Rows.Count, 2).End(xlUp).Row 
'or lastrow = Cells(Rows.Count, "B").End(xlUp).Row
End sub

should work. However I always prefer to specify at least the sheet first, to make sure my code run from anywhere, like:

Option Explicit
Sub LastrowExample2()
'declare variable lastrow as Long
Dim lastrow as Long
'declare sheet
 Dim ws As Worksheet
'get sheet
Set ws = ThisWorkbook.Worksheets("mysheetname") 
'get lastrow:
With ws
lastrow = .Cells(Rows.Count, 2).End(xlUp).Row 
'or lastrow = .Cells(Rows.Count, "B").End(xlUp).Row
End With
End sub
查看更多
爷、活的狠高调
3楼-- · 2019-08-21 08:07

Example

Option Explicit
Private Sub Example()
    With ThisWorkbook.Worksheets(1)
        Dim LAST_ROW As Long
            LAST_ROW = .Range("A" & .Rows.Count).End(xlUp).Row

        Debug.Print LAST_ROW ' Print on Immediate Window
    End With
End Sub

Multiple ways finding last row

Private Sub Example2()
    Dim Sht As Worksheet
    Set Sht = ActiveWorkbook.Sheets(1)

    Dim LAST_ROW As Long

    'Using Find
      LAST_ROW = Sht.Cells.Find("*", searchorder:=xlByRows, _
                                     searchdirection:=xlPrevious).Row

    'Using SpecialCells
      LAST_ROW = Sht.Cells.SpecialCells(xlCellTypeLastCell).Row

    'Ctrl + Shift + End
      LAST_ROW = Sht.Cells(Sht.Rows.Count, "A").End(xlUp).Row

    'UsedRange
      LAST_ROW = Sht.UsedRange.Rows(Sht.UsedRange.Rows.Count).Row

    'Using Named Range
      LAST_ROW = Sht.Range("MyNamedRange").Rows.Count

    'Ctrl + Shift + Down
      LAST_ROW = Sht.Range("A1").CurrentRegion.Rows.Count

End Sub
查看更多
登录 后发表回答