Attribute VB_Name = "ErrorPractice"
Option Explicit

Public Sub CheckSummarySheet()
    Dim ws As Worksheet, code As Long, detail As String
    On Error Resume Next
    Err.Clear
    Set ws = ThisWorkbook.Worksheets("월별집계")
    code = Err.Number
    detail = Err.Description
    On Error GoTo 0
    If code <> 0 Then
        Debug.Print code, detail
        MsgBox "월별집계 시트 조회 실패. 시트 이름을 확인하세요. 오류=" & CStr(code), vbExclamation
        Exit Sub
    End If
    ws.Range("A1").Value = "OK"
    MsgBox "월별집계!A1 = OK"
End Sub

Public Sub OpenPracticeFile()
    Dim wb As Workbook, openBook As Workbook, path As String
    Dim previousUpdating As Boolean, previousEvents As Boolean
    Dim previousSecurity As Long, code As Long, detail As String
    Dim cleanupCode As Long
    previousUpdating = Application.ScreenUpdating
    previousEvents = Application.EnableEvents
    previousSecurity = Application.AutomationSecurity
    On Error GoTo Failed
    If Len(ThisWorkbook.Path) = 0 Then Err.Raise vbObjectError + 1060, , "Save the practice XLSM first."
    path = ThisWorkbook.Path & Application.PathSeparator & "원본.xlsx"
    If Len(Dir$(path)) = 0 Then Err.Raise vbObjectError + 1061, , "Practice source is missing."
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.AutomationSecurity = 3
    For Each openBook In Application.Workbooks
        If StrComp(openBook.FullName, path, vbTextCompare) = 0 Then
            Err.Raise vbObjectError + 1062, , "Practice source is already open. Close it yourself before retrying."
        End If
    Next openBook
    Set wb = Workbooks.Open(path, UpdateLinks:=0, ReadOnly:=True)
    wb.Worksheets(1).Range("A1").Value = "검산"
    wb.Close SaveChanges:=False
    Set wb = Nothing
CleanUp:
    On Error Resume Next
    Err.Clear
    If Not wb Is Nothing Then wb.Close SaveChanges:=False
    cleanupCode = Err.Number
    Application.ScreenUpdating = previousUpdating
    Application.EnableEvents = previousEvents
    Application.AutomationSecurity = previousSecurity
    On Error GoTo 0
    If code <> 0 Then
        Debug.Print code, detail
        MsgBox "실행 중단. 연습 파일 위치와 접근 권한을 확인하세요. 오류=" & CStr(code), vbExclamation
    ElseIf cleanupCode = 0 Then
        MsgBox "정상 종료: 원본 파일을 저장하지 않았습니다."
    End If
    If cleanupCode <> 0 Then MsgBox "연습 파일 닫기 실패. 열린 파일을 확인하고 변경 내용을 저장하지 마세요.", vbExclamation
    Exit Sub
Failed:
    code = Err.Number
    detail = Err.Description
    Resume CleanUp
End Sub
