除了所有提到的方法之外,还有其他几种方法可以找到工作表或指定范围中的最后一行或最后一列。
Function FindingLastRow(col As String) As Long
'PURPOSE: Various ways to find the last row in a column or a range
'ASSUMPTION: col is passed as column header name in string data type i.e. "B", "AZ" etc.
Dim wks As Worksheet
Dim lstRow As Long
Set wks = ThisWorkbook.Worksheets("Sheet1") 'Please change the sheet name
'Set wks = ActiveSheet 'or for your problem uncomment this line
'Method #1: By Finding Last used cell in the worksheet
lstRow = wks.Range("A1").SpecialCells(xlCellTypeLastCell).Row
'Method #2: Using Table Range
lstRow = wks.ListObjects("Table1").Range.Rows.Count
'Method #3 : Manual way of selecting last Row : Ctrl + Shift + End
lstRow = wks.Cells(wks.Rows.Count, col).End(xlUp).Row
'Method #4: By using UsedRange
wks.UsedRange 'Refresh UsedRange
lstRow = wks.UsedRange.Rows(wks.UsedRange.Rows.Count).Row
'Method #5: Using Named Range
lstRow = wks.Range("MyNamedRange").Rows.Count
'Method #6: Ctrl + Shift + Down (Range should be the first cell in data set)
lstRow = wks.Range("A1").CurrentRegion.Rows.Count
'Method #7: Using Range.Find method
lstRow = wks.Column(col).Cells.Find("*", SearchOrder:=xlByRows, LookIn:=xlValues, SearchDirection:=xlPrevious).Row
FindingLastRow = lstRow
End Function
注意:请仅使用上述方法之一,因为它可以证明您的问题陈述。
请注意Find 方法看不到单元格格式,而只有数据,因此如果只有数据重要而不是格式,则查找 xlCellTypeLastCell。此外,合并单元格(必须避免)可能会给您带来意想不到的结果,因为它会给您第一个单元格的行号,而不是合并单元格中的最后一个单元格。