将 find LastRow 代码转换为函数

Convert find LastRow code into a function

我多次使用这段代码来获取最后的行号并且它工作正常,

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

我需要将它转换成一个函数,我尝试了以下但输出始终是 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

然后像这样使用

Dim i As Long: i = LR(ActiveSheet)
Debug.Print i

你的函数从来没有 return任何东西。

如果您希望它达到 return 值,您需要添加 LR = lastRow

或者只是 return 像这样(因为你根本没有使用 LastColumn):

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

最后一行函数

  • 如果工作表为空,结果将是0LR的初始值)。
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