why i use Worksheet.UsedRange.Rows.Count got wrong result

前端 未结 4 1947
孤城傲影
孤城傲影 2020-12-06 09:00

In VB.NET I want to get the used rows so I wrote that:

Dim objWorksheet As Excel.Worksheet = workbook.Sheets(2)
Dim lastRow = objWorksheet.UsedRange.Rows.Coun         


        
4条回答
  •  不知归路
    2020-12-06 09:34

    Sometimes it only appears too small. Say we have:

    and we run:

    Sub aRowsByAnyOtherName1()
        Dim N As Long
        N = ActiveSheet.UsedRange.Rows.Count
        MsgBox N
    End Sub
    

    We see:

    The reason we get 3 rather than 4 is that the top row of the worksheet is not in UsedRange!

    EDIT#1:

    If the "top" of the worksheet needs to be included then use:

    Sub aRowsByAnyOtherName2()
        Dim N As Long, rng As Range
        Set rng = ActiveSheet.UsedRange
        N = rng.Rows.Count + rng(1).Row - 1
        MsgBox N
    End Sub
    

提交回复
热议问题