Better way to find last used row

前端 未结 8 1087
情歌与酒
情歌与酒 2020-11-22 15:32

I am trying to make this way of finding the last row as I found the last column:

Sheets(\"Sheet2\").Cells(1,Sheets(\"Sheet2\").Columns.Count).End(xlToLeft).C         


        
相关标签:
8条回答
  • 2020-11-22 16:19

    I use the following function extensively. As pointed out above, using other methods can sometimes give inaccurate results due to used range updates, gaps in the data, or different columns having different row counts.

    Example of use:

    lastRow=FindRange("Sheet1","A1:A1000")
    

    would return the last occupied row number of the entire range. You can specify any range you want from single columns to random rows, eg FindRange("Sheet1","A100:A150")

    Public Function FindRange(inSheet As String, inRange As String) As Long
        Set fr = ThisWorkbook.Sheets(inSheet).Range(inRange).find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
        If Not fr Is Nothing Then FindRange = fr.row Else FindRange = 0
    End Function
    
    0 讨论(0)
  • 2020-11-22 16:23

    I use this routine to find the count of data rows. There is a minimum of overhead required, but by counting using a decreasing scale, even a very large result requires few iterations. For example, a result of 28,395 would only require 2 + 8 + 3 + 9 + 5, or 27 times through the loop, instead of a time-expensive 28,395 times.

    Even were we to multiply that by 10 (283,950), the iteration count is the same 27 times.

    Dim lWorksheetRecordCountScaler as Long
    Dim lWorksheetRecordCount as Long
    
    Const sDataColumn = "A"   '<----Set to column that has data in all rows (Code, ID, etc.)
    
        'Count the data records
        lWorksheetRecordCountScaler = 100000  'Begin by counting in 100,000-record bites
        lWorksheetRecordCount = lWorksheetRecordCountScaler
    
        While lWorksheetRecordCountScaler >= 1
    
            While Sheets("Sheet2").Range(sDataColumn & lWorksheetRecordCount + 2).Formula > " "
                lWorksheetRecordCount = lWorksheetRecordCount + lWorksheetRecordCountScaler
            Wend
    
            'To the beginning of the previous bite, count 1/10th of the scale from there
            lWorksheetRecordCount = lWorksheetRecordCount - lWorksheetRecordCountScaler
            lWorksheetRecordCountScaler = lWorksheetRecordCountScaler / 10
    
        Wend
    
        lWorksheetRecordCount = lWorksheetRecordCount + 1   'Final answer
    
    0 讨论(0)
提交回复
热议问题