Skip to content

Instantly share code, notes, and snippets.

@m-haketa
Last active March 31, 2018 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save m-haketa/13ee772abf6904f5c79fa9c0401a208e to your computer and use it in GitHub Desktop.
Save m-haketa/13ee772abf6904f5c79fa9c0401a208e to your computer and use it in GitHub Desktop.
VBAで最終行を取得
Sub 最終行取得テスト()
Debug.Print getLastRow(ActiveSheet)
End Sub
Private Function getLastRow(WS As Worksheet, Optional CheckCol As Long = 1) As Long
With WS
getLastRow = 0
'UsedrangeとCheckColの範囲が一致する場合のみ内容チェック
'一致していない場合は、CheckColにはデータが入っていないので内容チェックはしない
If Not Intersect(.UsedRange, .Columns(CheckCol)) Is Nothing Then
LastRow = .UsedRange.Row + .UsedRange.Rows.Count - 1
If LastRow > 1 Then
'メモリのムダだがわかりやすさ優先。1行目から配列に格納
buf = .Range(.Cells(1, CheckCol), .Cells(LastRow, CheckCol)).Value
For c = UBound(buf, 1) To 1 Step -1
If Not IsEmpty(buf(c, 1)) Then
getLastRow = c
Exit Function
End If
Next
'LastRowが1のときは、上の処理だとbufが配列にならないので別処理。
'1行目にデータが入っていれば返り値を修正
ElseIf Not IsEmpty(.Cells(1, CheckCol).Value) Then
getLastRow = 1
End If
End If
End With
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment