※はけたさん作のプロシージャをforkして改修
※別バージョンはこちら
-
-
Save furyutei/882ea936e08296e632adb9feb30ce02c to your computer and use it in GitHub Desktop.
VBAで最終行を取得
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sub 最終行取得テスト() | |
Debug.Print getLastRow(ActiveSheet, 1) | |
End Sub | |
Private Function getLastRow(WS As Worksheet, Optional CheckCol As Long = 1) As Long | |
getLastRow = 0 | |
'UsedrangeとCheckColの範囲が一致する場合のみ内容チェック | |
'一致していない場合は、CheckColにはデータが入っていないので内容チェックはしない | |
Set UR = Intersect(WS.UsedRange, WS.Columns(CheckCol)) | |
If UR Is Nothing Then Exit Function | |
Set lastCell = UR.Find("*", LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlPrevious) | |
If Not WS.AutoFilterMode Then | |
'AutoFilter無効時にはシンプルに最終行が決まる | |
If Not lastCell Is Nothing Then getLastRow = lastCell.Row | |
Exit Function | |
End If | |
'AutoFilter有効時には、Find()では非表示セルが対象にならない | |
'チェック範囲の絞り込み(表示セル中でデータ有りの最終行以降を対象) | |
If lastCell Is Nothing Then | |
firstRow = 1 | |
Else | |
firstRow = lastCell.Row | |
End If | |
lastRow = UR.Rows(UR.Rows.Count).Row | |
Set UR = WS.Range(WS.Cells(firstRow, CheckCol), WS.Cells(lastRow, CheckCol)) | |
With UR | |
If .Rows.Count > 1 Then | |
Buf = .Rows.Value | |
For c = .Rows.Count To 1 Step -1 | |
If Not IsEmpty(Buf(c, 1)) Then | |
getLastRow = .Rows(c).Row | |
Exit Function | |
End If | |
Next | |
'.Rows.Countが1のときは、上の処理だとBufが配列にならないので別処理。 | |
'1行目にデータが入っていれば返り値を修正 | |
ElseIf Not IsEmpty(.Rows.Value) Then | |
getLastRow = .Rows(.Rows.Count).Row | |
End If | |
End With | |
End Function |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment