2017-04-03 177 views
0

我想要第一行和最后一行使用非空白单元格。 我最后一排工作正常,第一排是胸围。建议感激。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 

回答

1

如果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

工程就像一个魅力 - 现在我必须走开并尝试理解它! – m4sterbunny

1

这条线的工作方式开始在B柱的底部,然后工作起来:

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

要在第一行,你需要在表的顶部开始,然后工作反而下降,而且检查的第一行没有任何关系:

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

注意,对于LASTROW公式假定存在同样B列的最后一个单元没有数据,我的公式firstR ow假定列B中至少有一个单元格具有值。

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 
相关问题