VBA - Range.Row.Count

前端 未结 10 1534
别那么骄傲
别那么骄傲 2020-12-24 13:23

I have written a simple code to illustrate my predicament.

Sub test()
    Dim sh As Worksheet
    Set sh = ThisWorkbook.Sheets(\"Sheet1\")

    Dim k As Lon         


        
10条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-24 13:47

    The best solution is to use

    Cells(Rows.Count, 1).End(xlUp).Row
    

    since it counts the number of cells until it finds the last one written.

    Unlike

    Range("A1", sh.Range("A1").End(xlDown)).Rows.Count
    

    what it does is select an "from-to" range and display the row number of the last one busy.
    A range implies two minimum values, so ... meanwhile A1 has a value of the range continues to count to the limit (1048576) then it is shown.

    Sub test()
    
    Dim sh As Worksheet
    Set sh = ThisWorkbook.Sheets(1)
    Dim k As Long
    
        k = Cells(Rows.Count, 1).End(xlUp).Row
        MsgBox k
    
        k = sh.Range("A1", sh.Range("A1").End(xlDown)).Rows.Count
        MsgBox k
    
    End Sub
    

提交回复
热议问题