VBA用数据标识第一行和最后一行

我想要非空白单元格的第一行和最后一行。 我最后一排工作正常,第一排是胸围。 build议感激。

Sub idDataRange() Dim firstRow As Long Dim lastRow As Long Sheets("fileNames").Select ' this has been adapted from a Stack overflow answer. lastRow unedited ' first row I changed Up to Down = NOT the solution! With ActiveSheet firstRow = .Range("B" & .Rows.Count).End(xlDown).row lastRow = .Range("B" & .Rows.Count).End(xlUp).row End With MsgBox "the first row is " & firstRow MsgBox "last row is " & lastRow End Sub 

如果B列中的值不是从公式派生的,则可以使用SpecialCells()

 Dim firstRow As Long Dim lastRow As Long With Sheets("fileNames").Columns("B") '<--| reference your sheet (activating it is bad practice!) column "B" range If WorksheetFunction.CountA(.Cells) = 0 Then '<--| if no data whatever MsgBox "Sorry: no data" Else With .SpecialCells(xlCellTypeConstants) '<--| reference its cells with constant (ie, not derived from formulas) values) firstRow = .Areas(1).Row lastRow = .Areas(.Areas.Count).Cells(.Areas(.Areas.Count).Rows.Count).Row End With MsgBox "the first row is " & firstRow MsgBox "last row is " & lastRow End If End With 

这条线从B列底部开始工作,然后工作:

 lastRow = .Range("B" & .Rows.Count).End(xlUp).row 

要find第一行,您需要从工作表的顶部开始,然后逐渐减less,而且还要检查第一行没有任何内容:

 firstRow = iif(isempty(.Range("B1")),.Range("B1").End(xlDown).row,1) 

请注意,lastRow的公式假定列B的最后一个单元格中没有数据。另外,我的firstRow公式假定列B中至less有一个单元格的值。

使用Find

编辑 :如果它是A1没有find第一个单元格。
我已经添加.Cells(.Rows.Count, .Columns.Count)到两个Find行。 如果表格中的最后一个单元格填充,它仍然会被删除 – 但是在19年之后,我从来没有用整个表格填充数据。

 Sub test() Dim rLastCell As Range MsgBox LastCell(Sheet1).Address 'Last Cell MsgBox LastCell(Sheet1, 1).Address 'First Cell. End Sub '--------------------------------------------------------------------------------------- ' Arguments : Direction = 2 :Find Last Cell, 1 :Find First Cell '--------------------------------------------------------------------------------------- Public Function LastCell(wrkSht As Worksheet, Optional Direction As Long = 2) As Range Dim lLastCol As Long, lLastRow As Long On Error Resume Next With wrkSht lLastCol = .Cells.Find("*", .Cells(.Rows.Count, .Columns.Count), , , xlByColumns, Direction).Column lLastRow = .Cells.Find("*", .Cells(.Rows.Count, .Columns.Count), , , xlByRows, Direction).Row If lLastCol = 0 Then lLastCol = 1 If lLastRow = 0 Then lLastRow = 1 Set LastCell = wrkSht.Cells(lLastRow, lLastCol) End With On Error GoTo 0 End Function