2017-04-03 298 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 
相關問題