EXCEL VBA 図形を含めて最終行や最終列を取得したい
EXCEL VBAで使用セルの最終行や最終列を取得したいとgoogle検索をすると
よく紹介されているのは、表の最終行や列を取得する方法。
しかし実際は図形が含まれているシートの使用最終行列を求めたい場合がある。
ばらばらに記載されていることが多かったためまとめて実装に近いものを記載する。
Option Explicit '強制変数宣言指定 Option Base 0 '配列の要素番号0から '最終行列取得タイプ Const cLineTypeRow As Integer = 0 Const cLineTypeCol As Integer = 1 Function getLastLine() Dim trgwsh As Worksheet Dim strMaxLine As Variant Dim shpMaxLine As Variant Dim EndRow As Long Dim EndCol As Long '最終行列を取得するワークシートを設定 Set trgwsh = ThisWorkbook.Worksheets(1) 'ターゲットワークシートの文字の最終行列を取得 strMaxLine = getLastStrLine(trgwsh) 'ターゲットワークシートのShapesオブジェクトの最終行列を取得 shpMaxLine = getLastShapeLine(trgwsh) '行列分解 EndRow = Application.Max(strMaxLine(cLineTypeRow), shpMaxLine(cLineTypeRow)) EndCol = Application.Max(strMaxLine(cLineTypeCol), shpMaxLine(cLineTypeCol)) 'デバッグ用出力 Debug.Print "最終行" & EndRow & "最終列" & EndCol '列をアルファベット変換 'Split(Cells(1, EndCol).Address(True, False), "$")(0) Debug.Print "最終行列セル" & Split(Cells(1, EndCol).Address(True, False), "$")(0) & EndRow End Function Function getLastStrLine(wsh As Worksheet) As Variant Dim EndLine(1) As Long 'UsedRangeで使用した履歴のあるセルを最終行列とする EndLine(cLineTypeRow) = wsh.UsedRange.Item(wsh.UsedRange.Count).Row EndLine(cLineTypeCol) = wsh.UsedRange.Columns(wsh.UsedRange.Columns.Count).Column getLastStrLine = EndLine End Function Function getLastShapeLine(wsh As Worksheet) As Variant Dim EndLine(1) As Long Dim shp As Shape If wsh.Shapes.Count > 0 Then 'Shapesオブジェクトの最終行を取得 For Each shp In wsh.Shapes EndLine(cLineTypeRow) = Application.Max(EndLine(cLineTypeRow), shp.BottomRightCell.Row) EndLine(cLineTypeCol) = Application.Max(EndLine(cLineTypeCol), shp.BottomRightCell.Column) Next Else '図形がない場合、A1を設定 EndLine(cLineTypeRow) = 1 EndLine(cLineTypeCol) = 1 End If getLastShapeLine = EndLine End Function