VBA使用数据识别第一行和最后一行

时间:2017-04-03 07:40:48

标签: excel vba excel-vba

我希望第一行和最后一行包含非空白单元格。 我的最后一行工作正常,第一排是破产。建议表示赞赏。

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

4 个答案:

答案 0 :(得分:2)

如果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 (i.e, 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

答案 1 :(得分:1)

此行的工作原理是从B列的底部开始,然后再进行处理:

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

要找到第一行,您需要从工作表的顶部开始,然后改为工作,同时检查第一行没有任何内容:

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

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

答案 2 :(得分:1)

使用Find

修改:如果第一个单元格为A1,则无法找到第一个单元格。
       我已将.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

答案 3 :(得分:-1)

'使用SELECTION功能

firstrow = Selection.Value

lastrow = Cells(Selection.Rows.Count + ActiveCell.Row-1,ActiveCell.Column)