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

前端 未结 4 1939
孤城傲影
孤城傲影 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:12

    Try to avoid UsedRange. It can be misleading. For instance, if you fill range A1:B5 and clear the contents of column B, then UsedRange.Columns.Count will return 2 - because Excel remembers cells with formatting and includes them into UsedRange.

    UPDATE

    To get real last column and row, use following code:

    lRealLastRow = _
        Cells.Find("*", Range("A1"), xlFormulas, , xlByRows, xlPrevious).Row
    lRealLastColumn = _
        Cells.Find("*", Range("A1"), xlFormulas, , xlByColumns, xlPrevious).Column
    

    UPDATE 2 img2

提交回复
热议问题