2017-04-03 8 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 

最初の行を見つけるには、シートの上部に開始して作業する必要がありますfirstRため、LASTROWための式は、列Bの非常に最後のセルにデータがないことを前提としていることを私の式を

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

注:ダウン代わりに、だけでなく、最初の行には何も持っていないことを確認しますowは、値を持つ列Bに少なくとも1つのセルがあることを前提としています。

1

Findを使用する:

編集は:最初のセルを見つけるためには表示されませんそれがA1ならば。
2つのFind行に.Cells(.Rows.Count, .Columns.Count)を追加しました。シート上の最後のセルにデータが入力されていても、それでも問題はありませんが、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 
関連する問題