VBA:如何分配查找最后一行代码到一个函数
我想分配查找最后一行代码到一个函数( Private Sub findLastRowFn
),以便我可以随时调用它。 我有一个正在运行的代码,但我不能将它分配给一个函数。
这是我想要分配给一个函数的代码
Dim LastRow As Long, LastCell As Range ' use Find function to get last row Set LastCell = .Cells.Find(What:="*", After:=.Cells(1), Lookat:=xlPart, LookIn:=xlFormulas, _ searchorder:=xlByRows, searchdirection:=xlPrevious, MatchCase:=False) If Not LastCell Is Nothing Then LastRow = LastCell.Row Else MsgBox "Error!", vbCritical End If
而这样的事情就是我想要达到的。
With ActiveWorkbook.Sheets("Sheet1") findLastRowFn .Range("BK2:BQ" & LastRow).Select borderMeFn alignLeftItalicFn End With
使用以下function:
Function findLastRowFn(ws As Worksheet) As Long Dim LastRow As Long, LastCell As Range ' use Find function to get last row Set LastCell = ws.Cells.Find(What:="*", After:=ws.Cells(1), Lookat:=xlPart, LookIn:=xlFormulas, _ searchorder:=xlByRows, searchdirection:=xlPrevious, MatchCase:=False) If Not LastCell Is Nothing Then findLastRowFn = LastCell.Row Else MsgBox "Error!", vbCritical End If End Function
在你的Sub
,使用:
LastRow = findLastRowFn(ActiveWorkbook.Sheets("Sheet1"))