Option Explicit

'===========================================================
' 部品_値変換_日付 / ConvertToDate
'   ・値（Variant）を、日付（Date）に変換して返す
'     → Converts a value (Variant) to a Date and returns it.
'
'   ・変換できない値は、False や空の値ではなく、原因を示すエラーで止まる（Err.Raise）
'     → A value that cannot be converted stops with an error naming the cause (no silent wrong value).
'===========================================================

'===========================================================
' ■区分 / Classification
'   ・基礎区分：土台 ／ 用途区分：取得 ／ 操作対象区分：セル（セルから取得した値を扱う）
'     → Base: foundation / Purpose: get / Target: cell (works on a value read from a cell)
'
' ■バージョン / Version
'   ・Version 1.0（2026-10-29）
'===========================================================

'===========================================================
' ■URL（WordPress部品ページ）
'   https://feelcodelab.com/vba_parts/converttodate/
'===========================================================

'===========================================================
' ■前提条件（AI誤動作防止の最重要項目） / Preconditions
'   ・【最重要】変換の前に、VLOOKUP値取得の戻り値が、見つからない（#N/A）場合でないかを、呼び出し側が確認する
'     → 確認の書き方：If IsError(v) Then MsgBox "見つかりませんでした": Exit Sub
'     → [MOST IMPORTANT] The caller checks IsError on the VLOOKUP result before converting.
'
'   ・日付（Date 型）は、そのまま返す。日付として読める文字列（"2026/10/29"、"2026-10-29" など）は、日付に変換する
'     → A Date is returned as it is; text that reads as a date is converted.
'
'   ・数値（シリアル値）は、日付と取り違えやすいため、変換できない値として、エラーで止まる（1018）
'     → Numbers (serial values) stop with error 1018 because they are easily mistaken for dates.
'
'   ・空白（Empty）・空文字・Null・エラー値（#N/A など）・True/False・オブジェクト・配列・日付として読めない文字列は、エラーで止まる（1018）
'     → Empty, empty text, Null, error values, Booleans, objects, arrays and text that is not a date stop with error 1018.
'
'   ・文字列の読み取りは、パソコンの地域設定に従う（"10/29" のように、年が無い文字列は、避ける）
'     → Text is read according to the PC's regional settings; avoid text without a year.
'
'   ・変換できない値は、原因を示すエラーで止まる（Err.Raise）。呼び出し側の起点で受けて、Err.Description を表示する
'       - 値が、日付に変換できない（日付として読めない・数値・空白・Null・エラー値・True/False など）（vbObjectError + 1018）
'     → Values that cannot be converted stop with an error naming the cause.
'
'   ・Offset / Find / Resize / With は禁止
'     → Offset, Find, Resize, and With statements are prohibited.
'===========================================================

'===========================================================
' ■依存関係（部品名明記） / Component Dependencies
'   ・他の部品を参照しない（土台）
'     → References no other component (foundation).
'
'   ・組み合わせ：VLOOKUP値取得 → 値変換_日付
'     （VLOOKUP値取得の戻り値を、IsError で確認してから、この部品で変換する）
'     → Typical combination: [GetVlookupValue] -> [ConvertToDate]
'===========================================================

'===========================================================
' ■依存関係（シート・表） / Sheet Dependencies
'   ・特定のシートや表には、依存しない（値を受け取って、型を変換するだけ。VLOOKUP値取得などの戻り値（Variant）を想定している）
'     → Does not depend on any specific sheet or table; it only converts the value it receives (typically the result of [GetVlookupValue]).
'===========================================================

'===========================================================
' ■技術解説 / Technical Notes
'
'   ・変換を、VLOOKUP値取得の中に入れず、別の部品にする理由
'       → 迷ったら分ける。取得する値の型は、呼び出し側が決める。また、型の変換は、VLOOKUP 以外
'          （セルの値の読み取りなど）にも使える。
'       → Conversion is separate (when in doubt, split); it is also usable for values from other sources.
'
'   ・数値を、日付として扱わない理由
'       → 45000 のような数値は、Excel では日付のシリアル値だが、数量や金額と取り違えやすい。日付として扱いたい値は、セルの書式を日付にして、Date 型で受け取る。
'       → A number like 45000 is a date serial in Excel but is easily confused with a quantity; use date-formatted cells.
'
'   ・変換できない値を、False や空の値で返さず、エラーで止める理由
'       → 値を返す部品は、戻り値で、失敗を表せない。誤った値のまま、処理が進まないように、原因を示すエラーで止める。
'       → A value-returning component cannot express failure in its return value, so it stops with an error.
'
'   ・On Error を使う箇所
'       → 文字列からの変換は、事前の確認をすり抜ける場合に備えて、その 1 行だけ On Error Resume Next で確認する（他は使わない）。
'===========================================================

'---------------------------------------------
' ■引数（型＋意味） / Arguments
'   vValue : 変換する値（Variant）。VLOOKUP値取得の戻り値や、セルの値
'            → The value to convert (Variant), e.g. the result of GetVlookupValue or a cell value.
'---------------------------------------------

'---------------------------------------------
' ■戻り値（型＋意味） / Return Value
'   Date : 変換した値
'            → The converted value.
'---------------------------------------------

'---------------------------------------------
' ■エラー / Errors (Err.Raise)
'   ・vbObjectError + 1018：値が、日付に変換できない（日付として読めない・数値・空白・Null・エラー値・True/False など）
'---------------------------------------------

'===========================================================
' ■禁止事項（AI向け） / Prohibitions
'   ・VLOOKUP値取得の戻り値を、IsError で確認せずに、この部品へ渡すことの禁止
'     → Do not pass the VLOOKUP result without checking IsError.
'
'   ・変換できない値を、エラーで止めずに、0 や空文字で代用することの禁止
'     → Do not substitute 0 or an empty string for a value that cannot be converted.
'
'   ・Offset禁止 / Find禁止 / Resize禁止 / With禁止
'     → Offset, Find, Resize, and With blocks are prohibited.
'===========================================================

'===========================================================
' ■使用例（サンプルコード） / Example
'   ◆VLOOKUP値取得の結果を変換する / Convert the result of GetVlookupValue◆
'   Dim v As Variant
'   Dim d As Date
'
'   v = 部品_VLOOKUP値取得(rng, "A-001", 6)
'   If IsError(v) Then MsgBox "見つかりませんでした": Exit Sub    '先に、見つからない場合を確認する
'
'   d = 部品_値変換_日付(v)                                    '変換できない値は、エラーで止まる
'
'   ※ 変換できない値の場合は、原因を示すエラーで止まる（起点で 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 vValue As Variant) As Date

    '本体処理（英語名）を呼び出し、結果をそのまま返す / Call core function and return its result
    部品_値変換_日付 = f_ConvertToDate(vValue)

End Function

'===========================================================
' ■本体処理（英語名） / Core Function
'   ・値（Variant）を、日付（Date）に変換して返す
'     → Converts a value (Variant) to a Date and returns it.
'===========================================================
Function f_ConvertToDate(ByVal vValue As Variant) As Date

    Dim s As String
    Dim errNo As Long

    f_ConvertToDate = 0

    If IsObject(vValue) Or IsArray(vValue) Then
        Err.Raise vbObjectError + 1018, "f_ConvertToDate", _
                  "値が、オブジェクトまたは配列のため、日付（Date）に変換できません。"
    End If

    If IsError(vValue) Then
        Err.Raise vbObjectError + 1018, "f_ConvertToDate", _
                  "値が、エラー値（#N/A など）のため、日付（Date）に変換できません" & _
                  "（VLOOKUP値取得の戻り値は、先に IsError で確認してください）。"
    End If

    If IsNull(vValue) Then
        Err.Raise vbObjectError + 1018, "f_ConvertToDate", _
                  "値が Null のため、日付（Date）に変換できません。"
    End If

    If IsEmpty(vValue) Then
        Err.Raise vbObjectError + 1018, "f_ConvertToDate", _
                  "値が空白（Empty）のため、日付（Date）に変換できません。"
    End If

    '---------------------------------------------
    ' ■型ごとに変換（日付はそのまま。文字列は、日付として読めるかを先に確認する。数値は変換しない）
    '   / Convert by type (a Date as it is; text only if it reads as a date; numbers are not converted)
    '---------------------------------------------
    Select Case VarType(vValue)

        Case vbDate
            f_ConvertToDate = vValue

        Case vbString
            s = Trim(vValue)
            If Len(s) = 0 Or IsDate(s) = False Then
                Err.Raise vbObjectError + 1018, "f_ConvertToDate", _
                          "文字列「" & Left(vValue, 50) & "」は、日付として読めないため、日付（Date）に変換できません。"
            End If

            On Error Resume Next
            f_ConvertToDate = CDate(s)
            errNo = Err.Number
            On Error GoTo 0

            If errNo <> 0 Then
                Err.Raise vbObjectError + 1018, "f_ConvertToDate", _
                          "文字列「" & Left(vValue, 50) & "」は、日付に変換できません。"
            End If

        Case Else
            Err.Raise vbObjectError + 1018, "f_ConvertToDate", _
                      "値の型（" & TypeName(vValue) & "）は、日付（Date）に変換できません" & _
                      "（数値は、日付と取り違えやすいため、変換しません）。"

    End Select

End Function

