Option Explicit

'===========================================================
' 部品_シート削除 / DeleteSheet
'   ・指定したシート（Worksheet）を、削除する
'     → Deletes the specified sheet (Worksheet).
'
'   ・削除の確認メッセージは、この部品の中だけで、止める（削除の直前に止めて、直後に、元の設定へ戻す）
'     → The confirmation dialog is suppressed only inside this component (turned off right before the delete and restored right after).
'
'   ※ この部品は Sub（プロシージャ）ではなく「Function（関数）」で、成功／失敗を Boolean で返す
'     → ※ This component is a Function (not a Sub) that returns success/failure as a Boolean.
'===========================================================

'===========================================================
' ■区分 / Classification
'   ・基礎区分：土台 ／ 用途区分：処理 ／ 操作対象区分：シート
'     → Base: foundation / Purpose: process / Target: sheet
'
' ■バージョン / Version
'   ・Version 1.0（2026-10-30）
'===========================================================

'===========================================================
' ■URL（WordPress部品ページ）
'   https://feelcodelab.com/vba_parts/deletesheet/
'===========================================================

'===========================================================
' ■前提条件（AI誤動作防止の最重要項目） / Preconditions
'   ・【最重要】この部品は Function（関数）であり、戻り値（Boolean）を返す
'     → 削除できた場合は True、実行時にできなかった場合は False（この場合は、エラーでは止まらない）
'     → 呼び出し側は、必ず戻り値を確認してから後続処理を行い、メッセージも呼び出し側で表示する
'       （False のときは、MsgBox のあとに Exit Sub まで書く）
'     → [MOST IMPORTANT] This component is a Function that returns a Boolean: True if it worked, False if it
'        failed at run time (no error is raised then). The caller must check the return value before the
'        following processing and show any message itself (write Exit Sub after the MsgBox).
'
'   ・【最重要】削除は、元に戻せない。確認メッセージも、出ない
'     → 削除してよいシートかを、呼び出し側で、必ず確認する（例：シート名を、シート存在チェックで確認してから、取得する）
'     → 削除したシートを指していた数式は、#REF! になる
'     → [MOST IMPORTANT] A deleted sheet cannot be restored and no confirmation is shown; the caller must make
'        sure the sheet may be deleted. Formulas referring to it become #REF!.
'
'   ・削除するシート（vWs）は、Worksheet で渡す
'     → ブックは、Worksheet が持っているので、ブックの引数は不要
'     → 削除したあとは、その Worksheet 変数は、使えない（使うと、エラーになる）
'     → Pass the sheet as a Worksheet; the variable must not be used after the delete.
'
'   ・削除の確認メッセージ（DisplayAlerts）は、この部品の中で、止めて、すぐ戻す
'     → 呼び出し前の設定（True か False か）を控えておき、削除の直後（失敗したときも）に、その設定へ戻す
'     → 高速化の部品は、DisplayAlerts を変えない。この部品が、自分で、止めて、戻す
'     → DisplayAlerts is turned off only around the delete and restored to its previous value (also on failure).
'
'   ・ブックの中の、表示されているシートが、これ 1 つだけの場合は、削除できず、False を返す（Excel の決まり）
'     → また、ブックの構成が、保護されているときも、削除できず、False を返す
'     → If it is the only visible sheet, or the workbook structure is protected, the delete fails and False is returned.
'
'   ・削除できなかった場合（実行時の失敗）は False を返す（原因は、イミディエイトウィンドウに出る）
'     → If it fails at run time, False is returned and the cause is printed.
'
'   ・非表示のシートも、削除できる
'     → A hidden sheet can also be deleted.
'
'   ・設定の誤りは、False ではなく、原因を示すエラーで止まる（Err.Raise）
'     - シート（vWs）が Nothing（vbObjectError + 1006）
'     → A Nothing sheet stops 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).
'
'   ・組み合わせ：シート存在チェック → シート削除
'     （削除するシートが、あるかを、先に確認する。ない場合に、シート名で取得すると、エラーになるため）
'     → Typical combination: [SheetExists] -> [DeleteSheet]
'
'   ・組み合わせ：高速化 → シート削除 → 高速化解除
'     （大本のプロシージャーで、エラー処理と、高速化解除を行う）
'     → Typical combination: [SpeedUp_On] -> [DeleteSheet] -> [SpeedUp_Off]
'
'===========================================================

'===========================================================
' ■依存関係（シート・表） / Sheet Dependencies
'   ・対象のシートは、Worksheet で渡す（ブックは、シートが持っているので、ブックの引数は不要）
'     → Pass the sheet as a Worksheet; no workbook argument is needed because the sheet knows its workbook.
'
'   ・ブックの中の、表示されているシートが、これ 1 つだけの場合は、削除できず、False を返す（Excel の決まり）
'     → If it is the only visible sheet in the workbook, the delete fails and False is returned (an Excel rule).
'
'   ・削除したシートを参照していた数式は、#REF! になる
'     → Formulas that referred to the deleted sheet become #REF!.
'===========================================================

'===========================================================
' ■技術解説 / Technical Notes
'
'   ・Worksheet で受け取る理由
'       → シートそのものを操作する部品は、Worksheet で受け取る（ルール 1-1）。シートは、自分のブックを持っているので、ブックの引数が要らない。
'       → A sheet-operating component receives a Worksheet; no workbook argument is needed.
'
'   ・DisplayAlerts を、この部品の中で、止めて、戻す理由
'       → 確認メッセージが出ると、マクロが、ユーザーの操作を待って、止まる。しかし、処理の全体で、確認を止めると、ほかの、大事な確認（上書き保存など）まで、黙って進んでしまう。必要な、削除の一瞬だけ、止めて、すぐ戻す。
'       → Turning confirmations off for the whole macro would also skip important prompts; only the delete is wrapped.
'
'   ・呼び出し前の設定を控えて、その設定へ戻す理由
'       → 呼び出し側が、すでに、DisplayAlerts を止めている場合に、True へ戻すと、呼び出し側の設定を、壊すため。
'       → If the caller had already turned it off, restoring True would break the caller's setting.
'
'   ・失敗したときも、設定を戻す理由
'       → 削除が失敗したときに、戻さないと、確認メッセージが、止まったままになる。エラー処理の中でも、戻している。
'       → Without restoring on failure the confirmations would stay off.
'
'   ・確認（削除してよいか）を、部品の中に入れない理由
'       → 削除してよいかは、呼び出し側の、判断による。迷ったら、分ける。確認が必要なときは、呼び出し側が、シート存在チェックなどを使う。
'       → Whether deletion is allowed is the caller's decision; when in doubt, split.
'
'   ・確認を On Error GoTo より前に置く理由
'       → On Error GoTo ErrHandler の有効な範囲でエラーを出すと、False に変えられてしまい、原因が伝わらない。
'       → Raising inside the On Error range would turn it into False and hide the cause.
'
'   ・Offset / Find / Resize / With を禁止する理由
'       → 生成AIが誤って不正な範囲操作を行う可能性が高く、行数可変の処理で誤動作を引き起こしやすいため。
'       → These statements often cause misaligned or ambiguous range operations when generated by AI.
'===========================================================

'---------------------------------------------
' ■引数（型＋意味） / Arguments
'   vWs         : 削除するシート（Worksheet）
'                  → The sheet to delete (Worksheet).
'---------------------------------------------

'---------------------------------------------
' ■戻り値（型＋意味） / Return Value
'   Boolean : 削除できた場合は True、実行時にできなかった場合は False
'             → True if deleted, False if it failed at run time.
'---------------------------------------------

'---------------------------------------------
' ■エラー / Errors (Err.Raise)
'   ・vbObjectError + 1006：シート（vWs）が Nothing
'---------------------------------------------

'===========================================================
' ■禁止事項（AI向け） / Prohibitions
'   ・Function を Sub（プロシージャ）に変更することの禁止
'     → Do not convert this Function into a Sub; the Boolean return value is essential.
'
'   ・戻り値（Boolean）を確認せずに後続処理を行うことの禁止
'     → Do not proceed without checking the Boolean return value.
'
'   ・Set していない Worksheet 変数を渡すことの禁止
'     → Do not pass a Worksheet variable that has not been set.
'
'   ・削除してよいシートかを、確認せずに、この部品を呼ぶことの禁止（削除は、元に戻せない）
'     → Do not call this without making sure the sheet may be deleted (it cannot be undone).
'
'   ・削除したあとの、Worksheet 変数を、使うことの禁止
'     → Do not use the Worksheet variable after the delete.
'
'   ・Application.DisplayAlerts を、止めたまま、にすることの禁止（止めたら、必ず、元の設定へ戻す）
'     → Do not leave Application.DisplayAlerts off; always restore the previous value.
'
'   ・Offset禁止 / Find禁止 / Resize禁止 / With禁止
'     → Offset, Find, Resize, and With blocks are prohibited.
'===========================================================

'===========================================================
' ■使用例（サンプルコード） / Example
'   ◆例1：作業用のシート「TEMP」を、削除する / Example 1: delete a work sheet named TEMP◆
'   If 部品_シート存在チェック(ThisWorkbook, "TEMP") Then
'       If 部品_シート削除(ThisWorkbook.Worksheets("TEMP")) = False Then
'           MsgBox "シートを削除できませんでした"
'           Exit Sub
'       End If
'   End If
'
'   ◆例2：高速化と、エラー処理を組み合わせる / Example 2: with the speed-up and error handling◆
'   （大本のプロシージャー → 部品を呼ぶプロシージャー → 部品、の 3 段。詳しくは、部品_高速化の使用例を参照）
'
'   ※ シートが Nothing の場合は、False ではなく、原因を示すエラーで止まる
'===========================================================

'===========================================================
' ■ラッパー関数（日本語名） / Wrapper Function
'   ・辞書の日本語名で呼び出すための窓口
'     → Entry point callable by the Japanese dictionary name.
'
'   ・内部では英語名の本体処理を呼び出し、結果（Boolean）をそのまま返す
'     → Internally calls the English-named core function and returns its result (Boolean) as it is.
'===========================================================
Function 部品_シート削除(ByVal vWs As Worksheet) As Boolean

    '本体処理（英語名）を呼び出し、結果をそのまま返す / Call core function and return its result
    部品_シート削除 = f_DeleteSheet(vWs)

End Function

'===========================================================
' ■本体処理（英語名） / Core Function
'   ・シートを削除する（確認メッセージは、この中だけで止める）
'     → Deletes the sheet (the confirmation is suppressed only inside).
'===========================================================
Function f_DeleteSheet(ByVal vWs As Worksheet) As Boolean

    Dim prevAlerts As Boolean

    f_DeleteSheet = False

    '---------------------------------------------
    ' ■シートが設定されているかを確認（Nothing の場合はエラーで止める）
    '   ※ On Error GoTo より前に置く（Err.Raise を False に変えず、呼び出し側へ届けるため）
    '   / Check that the sheet is set (stop with an error if Nothing);
    '     placed before On Error GoTo so that Err.Raise reaches the caller
    '---------------------------------------------
    If vWs Is Nothing Then
        Err.Raise vbObjectError + 1006, "f_DeleteSheet", _
                  "シート（vWs）が設定されていません（Nothing）。"
    End If

    '---------------------------------------------
    ' ■呼び出し前の、確認メッセージの設定を控える / Keep the current confirmation setting
    '---------------------------------------------
    prevAlerts = Application.DisplayAlerts

    '---------------------------------------------
    ' ■エラー時は ErrHandler へ（False を返す） / On error, jump to ErrHandler (returns False)
    '---------------------------------------------
    On Error GoTo ErrHandler

    '---------------------------------------------
    ' ■確認メッセージを止めて、削除し、すぐ元の設定へ戻す
    '   / Turn off the confirmation, delete, and restore the setting right away
    '---------------------------------------------
    Application.DisplayAlerts = False
    vWs.Delete
    Application.DisplayAlerts = prevAlerts

    f_DeleteSheet = True
    Exit Function

ErrHandler:
    Debug.Print "f_DeleteSheet: " & Err.Number & " " & Err.Description
    Application.DisplayAlerts = prevAlerts                  '失敗したときも、元の設定へ戻す / restore also on failure
    f_DeleteSheet = False

End Function

