Excel VBAで、空白を含んだ場合の最終行の取得を行いたかったのでメモ。
複数の列の最終行を取得して、一番大きい物を返す。
歯抜けになっていてもどこかの列の最終行を返す。下の例だと14を返す。
ソース
'***************************************************
' @fn データ最終行を取得
' @param I N:(lastColIndex) データ列の最終列
' @return 最終行番号
'***************************************************
Function GetLastRowIndex(ByVal lastColIndex As Long) As Long
Dim colIndex As Long ' 現在列
Dim wkIndex() ' 作業用配列
' データ列の全ての最終行を配列に格納
colIndex = 1 ' 最初の列
ReDim wkIndex(lastColIndex) ' 配列数定義
Do
wkIndex(colIndex - 1) = Cells(Rows.Count, colIndex).End(xlUp).Row
colIndex = colIndex + 1 ' 次の列へ
If colIndex > lastColIndex Then
Exit Do
End If
Loop
' 最終行で一番大きいものを格納する
Dim i As Long
Dim maxnum As Long: maxnum = -1 ' 最大値
For i = 0 To UBound(wkIndex)
If wkIndex(i) > maxnum Then
maxnum = wkIndex(i)
End If
Next i
GetLastRowIndex = maxnum
End Function
使い方
ヘッダ行が5行目、データ列が3列、データ行の始まりが6行目からあるとする。
'************************************
' クリアボタンクリック
'************************************
Sub ClearButton_Click()
Dim FastRowIndex As Long ' ヘッダを除くデータ行から
Dim lastRowIndex As Long ' 最終行
Dim res As VbMsgBoxResult
Dim lastColIndex As Long: lastColIndex = 3 ' 最終列
' res = MsgBox("データ行をクリアします。" & vbCr & "よろしいですか?", vbOKCancel)
' If res = vbCancel Then
' Exit Sub
' End If
' 最初のヘッダを除くデータ行を取得
FastRowIndex = Cells(1, 1).End(xlDown).Row + 1
' 最終行取得
lastRowIndex = GetLastRowIndex(lastColIndex) + 1
' データ行クリア
Range(Cells(FastRowIndex, 1), Cells(lastRowIndex, lastColIndex)).ClearContents
End Sub
●突き抜けたデータがあったり空白を含んでいても全ての最終行を削除してくれる
↓
この関数は、データを処理するときの最終行を取得するために使うのも良いかも。