如何知道vba(excel)中填入的最后一行?

时间:2015-04-15 14:55:10

标签: excel vba excel-vba

我有一个工作表调用“Recap”,我想知道我在这张表中有多少行。我试过这段代码:

Function FindingLastRow(Mysheet As String) As Long

Dim sht As Worksheet
Dim LastRow As Long

Set sht = ThisWorkbook.Worksheets(Mysheet) 
LastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row
FindingLastRow = LastRow

End Function

...

在我的宏中我试过这个:

...

Dim lastR As Long
lastR=FindingLastRow("Recap")
msgBox lastR

.....

4 个答案:

答案 0 :(得分:2)

您正在将字符串传递到FindingLastRow函数但未使用它。 shiit 是传入的参数,但您稍后尝试使用名为 Mysheet 的内容。

Function FindingLastRow(Optional MySheet As String, Optional sCOL as String = "A") As Long
    Dim sht As Worksheet
    Dim LastRow As Long

    If Not CBool(Len(MySheet)) Then MySheet = ActiveSheet.Name

    Set sht = ThisWorkbook.Worksheets(MySheet)
    LastRow = sht.Cells(sht.Rows.Count, sCOL).End(xlUp).Row
    FindingLastRow = LastRow
    Set sht = nothing
End Function

Sub test_FindingLastRow()
    Dim lastR As Long
    lastR = FindingLastRow
    MsgBox lastR
    lastR = FindingLastRow("Recap")
    MsgBox lastR
    lastR = FindingLastRow("Recap", "B")
    MsgBox lastR
End Sub

如果未传入工作表名称,则使用当前的ActiveSheet名称。如果没有传递字母列名称,则使用A列。

答案 1 :(得分:1)

如果您想查找ThisWorkbook以外的图书中的最后一个单元格:

Function FindingLastRow( _
  ByVal shtName As String, _
  Optional ByVal colLetter As Variant, _
  Optional ByRef wkBk As Variant _
  ) As Long

  Dim colId As String
  If IsMissing(colLetter) Then
     colId = "A"
  Else
     colId = colLetter
  End If

  Dim myTargBk As Excel.Workbook
  If IsMissing(wkBk) Then
     Set myTargBk = ThisWorkbook
  Else
     Set myTargBk = wkBk
  End If

  Dim sht As Worksheet
  Set sht = myTargBk.Worksheets(shtName)
  With sht
    FindingLastRow = .Cells(.Rows.Count, colId).End(Excel.xlUp).Row
  End With

End Function

像这样使用:

Sub findLast()
  MsgBox FindingLastRow("Sheet1")
End Sub

或者在另一个打开的工作簿中查找A列的最后一行...

Sub findLast2()
  Dim w As Excel.Workbook
  Set w = Excel.Workbooks("Norf.xlsx")
  MsgBox FindingLastRow("Sheet1", , w)
End Sub

或者在另一个打开的工作簿中找到 B 列的最后一行...

Sub findLast3()
  Dim w As Excel.Workbook
  Set w = Excel.Workbooks("Norf.xlsx")
  MsgBox FindingLastRow("Sheet1", "B", w)
End Sub

答案 2 :(得分:1)

你还假设最后一个单元格将在A列中,但可能不是这样,所以我倾向于恢复到这样:

Function FindingLastRow(sheetName As String) As Long
    FindingLastRow = Sheets("sheetName").Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row 
End Function

答案 3 :(得分:0)

Worksheet变量上的UsedRange在这里非常有用。你真的不需要UDF来获取行数。

LastRow = Worksheets("Recap").UsedRange.Rows.Count

如果您的数据在第1行开始且工作表在数据之外没有格式,则此方法仅适用。如果您知道数据从第1行以外的其他位置开始,则可以在起始行+ UsedRange.Cells(1,1).Row中添加。第二个问题会阻止使用UsedRange。