Option Explicit

'===========================================================
' ■部品_最終行取得 / GetLastRow
'   ・指定したブックの、指定したシートの、指定列の「データが入っている最後の行番号」を返す関数
'     → Returns the last used row number in the specified column of the specified sheet of the specified workbook.
'
'   ・xlUp を用いるため、空白が混在していても確実に最終行を取得できる
'     → Uses xlUp to reliably detect the last used row even when blank cells exist.
'
'   ・行数が可変の列を扱うループ処理や、範囲の終了行を決める処理で使用することが多い
'     → Commonly used for loops over variable-length columns and for deciding the end row of a range.
'===========================================================

'===========================================================
' ■区分 / Classification
'   ・基礎区分：土台 ／ 用途区分：取得 ／ 操作対象区分：シート
'     → Base: foundation / Purpose: get / Target: sheet
'
' ■バージョン / Version
'   ・Version 1.0（2026-10-27）
'===========================================================

'===========================================================
' ■URL（WordPress部品ページ）
'   https://feelcodelab.com/vba_parts/getlastrow/
'===========================================================

'===========================================================
' ■前提条件（AI誤動作防止の最重要項目） / Preconditions
'   ★【最重要】ブック（vWb）とシート名（vSheetName）は、必ず引数で指定する（省略できない）
'     → ThisWorkbook ＝ このマクロが入っているブック ／ ActiveWorkbook ＝ いまアクティブなブック
'     → ファイルを開く部品の後は、ActiveWorkbook が、開いたファイルに切り替わる。
'       開いた直後に、ActiveWorkbook を変数へ控えて、その変数を渡す
'     → ★ [MOST IMPORTANT] The workbook (vWb) and the sheet name (vSheetName) must always be specified
'        (they cannot be omitted). After the "open file" component runs, ActiveWorkbook switches to the opened
'        file, so keep it in a variable right after opening and pass that variable.
'
'   ・対象は縦方向の1列である（列番号で指定する）
'     → The target is a single vertical column, specified by column number.
'
'   ・ヘッダー行を含めた最終行番号を返す（ヘッダー除外は呼び出し側で行う）
'     → Returns the last row including the header; header exclusion is handled by the caller.
'
'   ・データが1件もない場合は 1 が返る
'     → If no data exists, the function returns 1.
'
'   ・設定の誤りは、原因を示すエラーで止まる（Err.Raise）
'     → Setting mistakes stop with an error naming the cause (see "Errors" below).
'
'   ・Offset / Find / Resize / With は禁止
'     → Offset, Find, Resize, and With statements are prohibited.
'===========================================================

'===========================================================
' ■依存関係（部品同士） / Component Dependencies
'   ・なし（土台の部品。他の部品を参照しない。単独で使用可能）
'     → No required dependencies; this is a foundation component and is standalone.
'
'   ・他の部品から呼ばれる側（例：f_GetLastRow → f_SetRange_Fixed に渡す終了行を作る）
'     → Commonly called by other components, or used to make the end row passed to [SetRange_Fixed].
'===========================================================

'===========================================================
' ■依存関係（シート・表） / Sheet Dependencies
'   ・特になし
'     → No sheet-level dependencies.
'===========================================================

'===========================================================
' ■技術解説 / Technical Notes
'
'   ・ブックとシート名を、必ず引数で受け取る理由
'       → シート名だけでは、どのブックのシートか決まらず、Worksheets("名前") は、そのときの
'          ActiveWorkbook のシートを指してしまう。ファイルを開くと ActiveWorkbook が切り替わるため、
'          取り違えが起きやすい。ブックを必ず引数で渡す形にすると、呼び出しの行に
'          「どのブックの、どのシートか」が書かれ、読むだけで意図が分かる。
'       → A sheet name alone does not identify the workbook, and Worksheets("name") would refer to the current
'          ActiveWorkbook, which switches when a file is opened. Always passing the workbook makes the call
'          itself say "which sheet of which workbook".
'
'   ・シートを、Worksheet ではなく、シート名で受け取る理由
'       → 存在しないシートを Worksheets("名前") で取得すると、部品に入る前に、呼び出し側で
'          「インデックスが有効範囲にありません」のエラーになる。名前で受け取り、部品の中で
'          存在確認を行うことで、どのシートが存在しないのかを示すエラーにできる。
'       → Getting a missing sheet with Worksheets("name") would raise "Subscript out of range" on the caller side
'          before the component runs; receiving the name and checking it inside lets the error name the sheet.
'
'   ・シートの存在確認を、部品の中に直接書いている理由
'       → 土台の部品は、他の部品（シート存在チェック）を参照しない決まりのため。
'          数行が他の土台と重複するが、1つの部品だけをコピーして使えることを優先している。
'       → A foundation component does not reference other components (SheetExists). The few duplicated lines
'          let this one component be copied and used on its own.
'
'   ・Cells(Rows.Count, vColNum).End(xlUp).Row を使う理由
'       → Excelの最終行（1,048,576行）から上方向に検索することで、
'          空白が混在していても「最後にデータが入っている行」を確実に取得できる。
'       → Searching upward from the bottom row ensures reliable detection of the last used row
'          even when blank cells exist in the column.
'
'   ・データが1件もない場合に 1 を返す理由
'       → End(xlUp) は最終行から上に向かって最初に見つかったセルを返すため、
'          データがない場合は1行目が返る仕様となる。
'       → End(xlUp) returns the first non-empty cell from the bottom, so when no data exists, row 1 is returned.
'
'   ・ヘッダー行を含めて返す理由
'       → 多くの部品（転記系・検索系）が「ヘッダー込みの行番号」を前提としているため、
'          本部品はヘッダー除外処理を行わず、呼び出し側に委ねている。
'       → Many components assume header-inclusive row numbers, so header exclusion is delegated to the caller.
'
'   ・Offset / Find / Resize / With を禁止する理由
'       → 生成AIが誤って不正な範囲操作を行う可能性が高く、
'          行数可変の処理で誤動作を引き起こしやすいため。
'       → These statements often cause misaligned or ambiguous range operations
'          when generated by AI, leading to unpredictable behavior.
'
'   ・本部品が「土台」である理由
'       → 転記処理・検索処理・行ループ処理など、可変行を扱う多くの部品が最終行取得を必要とし、
'          しかも他の部品を参照せずに単独で動くため。
'       → Many variable-length operations need the last row, and this component works on its own
'          without referencing other components.
'===========================================================

'---------------------------------------------
' ■引数（型＋意味） / Arguments
'   vWb        : 対象のブック（Workbook）※必須（省略できない）
'                → Target workbook (Workbook); required.
'
'   vSheetName : 対象のシート名（String）
'                → Target sheet name (String).
'
'   vColNum    : 対象の列番号（Long）
'                → Target column number (Long).
'---------------------------------------------

'---------------------------------------------
' ■戻り値（型＋意味） / Return Value
'   Long : 指定列でデータが入っている最終行の行番号（データがないときは 1）
'          → Row number of the last used cell in the specified column (1 if there is no data).
'---------------------------------------------

'---------------------------------------------
' ■エラー / Errors (Err.Raise)
'   ・vbObjectError + 1010：ブック（vWb）が Nothing
'   ・vbObjectError + 1011：シート（vSheetName）が、ブックに存在しない
'   ・vbObjectError + 1007：列番号（vColNum）が 1 未満
'   ・vbObjectError + 1009：列番号（vColNum）が、シートの列数の上限を超えている
'---------------------------------------------

'===========================================================
' ■禁止事項（AI向け） / Prohibitions
'   ・ブックとシート名を省略することの禁止（必ず引数で指定する）
'     → Do not omit the workbook and the sheet name; always specify them.
'
'   ・Worksheets("名前") で取得したシートを、そのまま渡すことの禁止（シート名の文字列を渡す）
'     → Do not pass a sheet obtained with Worksheets("name"); pass the sheet name as a string.
'
'   ・セル参照禁止（Range("A1") など）
'     → Direct cell reference is prohibited; AI tends to generate incorrect fixed references.
'
'   ・Offset禁止
'     → Offset may cause misaligned row calculations.
'
'   ・Find禁止
'     → Find leads to unpredictable search behavior.
'
'   ・Resize禁止
'     → Resize may unintentionally expand ranges.
'
'   ・With禁止
'     → With blocks cause ambiguous object references.
'===========================================================

'===========================================================
' ■使用例（サンプルコード） / Example
'   ＜例1：マクロのファイル（ThisWorkbook）の「データ」シートの、1列目の最終行 / Example 1: macro file＞
'   Dim lastRow As Long
'
'   lastRow = 部品_最終行取得(ThisWorkbook, "データ", 1)
'
'   ＜例2：開いたファイルの最終行 / Example 2: an opened file＞
'   Dim wbSrc As Workbook
'   Dim lastRow As Long
'
'   If 部品_ファイルを開く("E:\TEST\売上.xlsx") = False Then Exit Sub
'   Set wbSrc = ActiveWorkbook                          '開いた直後に控える / keep it right after opening
'
'   lastRow = 部品_最終行取得(wbSrc, "売上", 2)         '2列目で最終行を取得 / by column 2
'
'   ※ シート名が存在しない場合は、シート名とブック名を示すエラーで止まる
'      （起点の On Error で受けて、Err.Description を表示する）
'===========================================================

'===========================================================
' ■ラッパー関数（日本語名） / Wrapper Function
'   ・辞書の日本語名で呼び出すための窓口
'     → Entry point callable by the Japanese dictionary name.
'
'   ・内部では英語名の本体処理を呼び出し、結果をそのまま返す
'     → Internally calls the English-named core function and returns its result as it is.
'===========================================================
Function 部品_最終行取得( _
        ByVal vWb As Workbook, _
        ByVal vSheetName As String, _
        ByVal vColNum As Long) As Long

    '本体処理（英語名）を呼び出し、結果をそのまま返す / Call core function and return its result
    部品_最終行取得 = f_GetLastRow(vWb, vSheetName, vColNum)

End Function

'===========================================================
' ■本体処理（英語名） / Core Function
'   ・指定したブックの、指定したシートの、指定列の最終行番号を返す
'     → Returns the last used row in the specified column of the specified sheet.
'
'   ・Cells(Rows.Count, vColNum).End(xlUp).Row を使用
'     → Uses Cells(Rows.Count, vColNum).End(xlUp).Row for detection.
'===========================================================
Function f_GetLastRow( _
        ByVal vWb As Workbook, _
        ByVal vSheetName As String, _
        ByVal vColNum As Long) As Long

    Dim ws As Worksheet

    '---------------------------------------------
    ' ■ブックが設定されているかを確認（Nothing の場合はエラーで止める）
    '   / Check that the workbook is set (stop with an error if Nothing)
    '---------------------------------------------
    If vWb Is Nothing Then
        Err.Raise vbObjectError + 1010, "f_GetLastRow", _
                  "ブック（vWb）が設定されていません（Nothing）。"
    End If

    '---------------------------------------------
    ' ■シートの存在を確認（存在しない場合は、シート名とブック名を示すエラーで止める）
    '   / Check that the sheet exists (stop with an error naming the sheet and workbook)
    '---------------------------------------------
    On Error Resume Next
    Set ws = vWb.Worksheets(vSheetName)
    On Error GoTo 0

    If ws Is Nothing Then
        Err.Raise vbObjectError + 1011, "f_GetLastRow", _
                  "シート「" & vSheetName & "」が、ブック「" & vWb.Name & "」に存在しません。"
    End If

    '---------------------------------------------
    ' ■列番号を確認（誤りは、原因を示すエラーで止める）
    '   / Check the column number (stop with an error naming the cause)
    '---------------------------------------------
    If vColNum < 1 Then
        Err.Raise vbObjectError + 1007, "f_GetLastRow", _
                  "列番号は 1 以上を指定してください（列番号=" & vColNum & "）。"
    End If

    If vColNum > ws.Columns.Count Then
        Err.Raise vbObjectError + 1009, "f_GetLastRow", _
                  "列番号がシートの列数の上限（" & ws.Columns.Count & "）を超えています（列番号=" & vColNum & "）。"
    End If

    '---------------------------------------------
    ' ■最終行の取得 / Get the last row
    '---------------------------------------------
    f_GetLastRow = ws.Cells(ws.Rows.Count, vColNum).End(xlUp).Row

End Function
