2014-12-30 2 views
4

코드에 오류가 없는데도 Errorhandler 프로 시저가 아직 실행 중입니다. 이상한 점은 문제 일 수 있습니다. ?오류 발생시 오류 발생 없음에도 불구하고 오류 GoTo 문이 여전히 실행 중임

오류 처리기없이 코드를 실행해도 오류는 발생하지 않지만 오류 처리 문을 포함하면 Errorhandler 아래의 msgbox 여전히 표시됩니다!

코드

Public Sub ExportGraphs(Optional PivotExport As Boolean) 
' Exports only graphs on the "Mainwindow" sheet to a new worksheet 

    Dim wsh As Worksheet: Set wsh = Sheets.Add 
    Dim source_sht As Worksheet: Set source_sht = Sheets("Mainwindow") 

    ActiveWindow.Zoom = 70 


    On Error GoTo Errorhandler 
    With wsh 

     If source_sht.OLEObjects("Btn_CurrentTime").Object.Value = True Then 
     .Name = source_sht.OLEObjects("CombBox_Instruments").Object.Value & " " & source_sht.OLEObjects("DTPicker_FROM").Object.Value _ 
       & "-" & source_sht.OLEObjects("DTPicker_TO").Object.Value 
     Else 
     .Name = source_sht.OLEObjects("CombBox_Instruments").Object.Value & " " & "Max_Possible_To" _ 
       & "-" & source_sht.OLEObjects("DTPicker_TO").Object.Value 

     End If 

    End With 

    Dim source_chart As ChartObject 
    Dim target_rng As Range: Set target_rng = wsh.Range("A1") 

    For Each source_chart In source_sht.ChartObjects 
     source_chart.CopyPicture xlScreen, xlBitmap 
     target_rng.PasteSpecial 
     Set target_rng = target_rng.Offset(20, 0) 
     Next 

    If PivotExport = True Then 

    Debug.Print "se" 

    End If 

Errorhandler: 
     MsgBox "An export sheet for this ticker and timeline already exists" 

End Sub 
+4

단순히'''Errorhandler :'''레이블 앞에''Exit Sub'''를 넣으십시오. 또는''If Err.Number <> 0를 추가하십시오. 그러면 MsgBox ...'''. 예 : 자세한 정보 http://www.cpearson.com/excel/errorhandling.htm – dee

답변

3

@dee는 정답을 제공했다.

Errorhandler:은 단지 장소 소유자입니다. 당신이 생각하는 것처럼 작동하지 않습니다. 당신은 If... Then... 문처럼 사용하는 다음의 ErrorHandler로

If Error Then 
    Show MsgBox 
Else 
    Skip MsgBox 
End If 

그냥 자리 아닌 If... Then... 자리 표시 자에 관계없이 오류 또는 오류없이의 실행 후 코드입니다. 이 문제를 해결하려면 Errorhandler: 라인 위의 Exit Sub을 추가

Exit Sub 

Errorhandler: 
    MsgBox "An export sheet for this ticker and timeline already exists" 

End Sub 
4

를이 코드 조각에서, ErrorHandler:line label로 알려져 있습니다 것입니다.

Errorhandler: 
     MsgBox "An export sheet for this ticker and timeline already exists" 

End Sub 

라인 라벨이없는 실행 코드,하지만 어떤GoTo Statement를 통해 점프하는 다른 코드를 알 수 있습니다 아니라 단지 마커입니다. 이 지식으로 무장 한 이들은 분명히 오류 처리기에만 국한되지 않습니다.

여기 해결책은 "초기"Sub에서 돌아 가기 위해 Exit Statement을 사용하는 것입니다.

Exit Sub 

Errorhandler: 
     MsgBox "An export sheet for this ticker and timeline already exists" 

End Sub 

다른 사람들은 나와 함께 동의 할 수 있습니다,하지만 난 코드 항상Exit Sub에 실행을 중지 있도록 내 오류 처리를 구축하고 싶다. 코드의 실행이 End Sub에서 종료되면 문제가 발생합니다.