Search code examples
vbaexcel

Return last row if there exists data in the sheet


I am writing a function which will check if the already existing sheet is new or has data. If it consists data then it should return the last row, else it must return the first row. I am using the following code:

Private Function GetLastRow(sheetName As String) As Integer
Dim lastRow As Integer
lastRow = CurrentWorkbook.Sheets(sheetName).Cells.Find(What:="*", _
                After:=Range("A1"), _
                LookAt:=xlPart, _
                LookIn:=xlFormulas, _
                SearchOrder:=xlByRows, _
                SearchDirection:=xlPrevious, _
                MatchCase:=False).End(xlUp).Row

GetLastRow = lastRow
End Function

But on debugging, I get an error that says that there is no object set. Is there any error in my code?


Solution

  • Like this

    Option Explicit
        
    Public Sub TEST()
        Debug.Print GetLastRow(ActiveSheet.Name)
    End Sub
    
    Private Function GetLastRow(ByVal sheetName As String) As Long
        Dim lastRow As Long
        
        With ActiveWorkbook.Sheets(sheetName)
            On Error GoTo returnVal
            lastRow = .Cells.Find(What:="*", _
                                  After:=.Range("A1"), _
                                  LookAt:=xlPart, _
                                  LookIn:=xlFormulas, _
                                  SearchOrder:=xlByRows, _
                                  SearchDirection:=xlPrevious, _
                                  MatchCase:=False).Row
        End With
        GetLastRow = lastRow
        
    Exit Function
    returnVal:
        GetLastRow = 1
    End Function