Error GoTo statement still executes, although no error occurs

I have my code below, it is strange that the procedure Errorhandleris still running, even if there are no errors in the code ... What could be the problem?

Running the code without any error handlers does not cause errors, but still appears msgboxin the section Errorhandlerwhen I include the error handling instructions!

the code

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
source share
2 answers

@dee provided the correct answer.

Errorhandler:- it's just a place. It does not work as you think. You use it as an operator If... Then...:

If Error Then
   Show MsgBox
Else
    Skip MsgBox
End If

, If... Then..., . , Exit Sub Errorhandler::

Exit Sub

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

End Sub
+3

ErrorHandler: .

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

End Sub

, , , GoTo Statement. , , , .

, Exit Statement Sub "early".

Exit Sub

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

End Sub

, , Exit Sub. End Sub, - .

+4

Source: https://habr.com/ru/post/1569440/


All Articles