Option Explicit

'===========================================================
' 部品_値変換_文字列 / ConvertToString
'   ・値（Variant）を、文字列（String）に変換して返す
'     → Converts a value (Variant) to a String 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/converttostring/
'===========================================================

'===========================================================
' ■前提条件（AI誤動作防止の最重要項目） / Preconditions
'   ・【最重要】変換の前に、VLOOKUP値取得の戻り値が、見つからない（#N/A）場合でないかを、呼び出し側が確認する
'     → 確認の書き方：If IsError(v) Then MsgBox "見つかりませんでした": Exit Sub
'     → [MOST IMPORTANT] The caller checks IsError on the VLOOKUP result before converting.
'
'   ・空白のセルの値（Empty）は、空文字（""）に変換する
'     → An empty cell value (Empty) becomes an empty string ("").
'
'   ・日付（Date 型）は、"yyyy/mm/dd" の形の文字列にする（時刻があるときは "yyyy/mm/dd hh:nn:ss"、時刻だけのときは "hh:nn:ss"）。
'     パソコンの地域設定に、結果が左右されないようにするため
'     → A Date becomes "yyyy/mm/dd" (with time if it has one), independent of the PC's regional settings.
'
'   ・数値・True/False は、VBA の CStr と同じ結果の文字列にする（例：1.5 → "1.5"）
'     → Numbers and Booleans give the same text as CStr.
'
'   ・エラー値（#N/A など）・Null・オブジェクト・配列は、変換できない値として、エラーで止まる（1018）
'     → Error values, Null, objects and arrays cannot be converted and stop with error 1018.
'
'   ・変換できない値は、原因を示すエラーで止まる（Err.Raise）。呼び出し側の起点で受けて、Err.Description を表示する
'       - 値が、変換できない（エラー値・Null・オブジェクト・配列）（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] -> [ConvertToString]
'===========================================================

'===========================================================
' ■依存関係（シート・表） / 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.
'
'   ・日付を、CStr ではなく、決まった形（yyyy/mm/dd）の文字列にする理由
'       → CStr は、パソコンの地域設定によって、日付の形が変わる。決まった形にすると、どのパソコンでも、同じ結果になる。
'       → CStr depends on regional settings; a fixed format gives the same result on any PC.
'
'   ・変換できない値を、False や空の値で返さず、エラーで止める理由
'       → 値を返す部品は、戻り値で、失敗を表せない。誤った値のまま、処理が進まないように、原因を示すエラーで止める。
'       → A value-returning component cannot express failure in its return value, so it stops with an error.
'
'===========================================================

'---------------------------------------------
' ■引数（型＋意味） / Arguments
'   vValue : 変換する値（Variant）。VLOOKUP値取得の戻り値や、セルの値
'            → The value to convert (Variant), e.g. the result of GetVlookupValue or a cell value.
'---------------------------------------------

'---------------------------------------------
' ■戻り値（型＋意味） / Return Value
'   String : 変換した値
'            → The converted value.
'---------------------------------------------

'---------------------------------------------
' ■エラー / Errors (Err.Raise)
'   ・vbObjectError + 1018：値が、変換できない（エラー値・Null・オブジェクト・配列）
'---------------------------------------------

'===========================================================
' ■禁止事項（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 s As String
'
'   v = 部品_VLOOKUP値取得(rng, "A-001", 3)
'   If IsError(v) Then MsgBox "見つかりませんでした": Exit Sub    '先に、見つからない場合を確認する
'
'   s = 部品_値変換_文字列(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 String

    '本体処理（英語名）を呼び出し、結果をそのまま返す / Call core function and return its result
    部品_値変換_文字列 = f_ConvertToString(vValue)

End Function

'===========================================================
' ■本体処理（英語名） / Core Function
'   ・値（Variant）を、文字列（String）に変換して返す
'     → Converts a value (Variant) to a String and returns it.
'===========================================================
Function f_ConvertToString(ByVal vValue As Variant) As String

    Dim s As String

    f_ConvertToString = ""

    If IsObject(vValue) Or IsArray(vValue) Then
        Err.Raise vbObjectError + 1018, "f_ConvertToString", _
                  "値が、オブジェクトまたは配列のため、文字列に変換できません。"
    End If

    If IsError(vValue) Then
        Err.Raise vbObjectError + 1018, "f_ConvertToString", _
                  "値が、エラー値（#N/A など）のため、文字列に変換できません" & _
                  "（VLOOKUP値取得の戻り値は、先に IsError で確認してください）。"
    End If

    If IsNull(vValue) Then
        Err.Raise vbObjectError + 1018, "f_ConvertToString", _
                  "値が Null のため、文字列に変換できません。"
    End If

    '---------------------------------------------
    ' ■空白（Empty）は、空文字を返す / Empty returns an empty string
    '---------------------------------------------
    If IsEmpty(vValue) Then Exit Function

    '---------------------------------------------
    ' ■日付は、決まった形の文字列にする / A Date becomes a fixed-format string
    '---------------------------------------------
    If VarType(vValue) = vbDate Then
        If CDbl(vValue) < 1 Then
            s = Format(vValue, "hh:nn:ss")
        ElseIf CDbl(vValue) = Int(CDbl(vValue)) Then
            s = Format(vValue, "yyyy/mm/dd")
        Else
            s = Format(vValue, "yyyy/mm/dd hh:nn:ss")
        End If
        f_ConvertToString = s
        Exit Function
    End If

    f_ConvertToString = CStr(vValue)

End Function

