LoginSignup
7
5

More than 5 years have passed since last update.

Excel VBAで複数列で最終行を取得する関数

Last updated at Posted at 2015-11-10

Excel VBAで、空白を含んだ場合の最終行の取得を行いたかったのでメモ。
複数の列の最終行を取得して、一番大きい物を返す。

下の例だと12を返す。
get1.png

歯抜けになっていてもどこかの列の最終行を返す。下の例だと14を返す。
get2.png

ソース

'***************************************************
' @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

●ヘッダを除くデータ行の値を全て削除してくれる。
クリア1.png

クリア2.png

●突き抜けたデータがあったり空白を含んでいても全ての最終行を削除してくれる
クリア3.png

クリア4.png

この関数は、データを処理するときの最終行を取得するために使うのも良いかも。

7
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5