2

I use this code to get the last row number.

Dim sh As Worksheet: Set sh = ActiveSheet
Dim lastRow As Long
lastRow = sh.Cells.Find("*", LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

I need to convert it into a function, I tried the following but the output is always 0.

Function LR(sh As Worksheet) As Long
    Dim lastRow As Long, LastColumn As Long
    lastRow = sh.Cells.Find("*", LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
End Function

And using like this

Dim i As Long: i = LR(ActiveSheet)
Debug.Print i
Community
  • 1
  • 1
Waleed
  • 847
  • 1
  • 4
  • 18
  • Further readings at SO: [Error in finding last used cell in Excel with VBA](https://stackoverflow.com/questions/11169445/error-in-finding-last-used-cell-in-excel-with-vba/11169920#11169920) – T.M. Jun 01 '22 at 09:22

2 Answers2

2

Your function never returns anything.

You need to add LR = lastRow if you want it to return the value.

Or just return it like this (since you aren't using LastColumn anyway):

Function LR(sh As Worksheet) As Long
   LR = sh.Cells.Find("*", LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
End Function
braX
  • 11,506
  • 5
  • 20
  • 33
1

Last Row Function

  • If the worksheet is empty, the result will be 0 (the initial value of LR).
Sub LRtest()
    Debug.Print LR(ThisWorkbook.Worksheets("Sheet1"))
End Sub

Function LR(ByVal ws As Worksheet) As Long
    ' Since this will fail if the worksheet is filtered, you could add...
    'If ws.FilterMode Then ws.ShowAllData ' ... to remove any filters.
    Dim lCell As Range
    Set lCell = ws.UsedRange.Find("*", , xlFormulas, , xlByRows, xlPrevious)
    If Not lCell Is Nothing Then LR = lCell.Row
End Function
VBasic2008
  • 44,888
  • 5
  • 17
  • 28