Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On Error GoTo statement is still executing although there is no error generated [duplicate]

I have my code below, the strange thing is that the Errorhandler procedure is still executing even though there are no errors in the code... What can be the issue?

Running the code without any errorhandlers generates no errors, but still the msgbox under Errorhandler shows up when I include an error handling statement!

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
like image 734
uncool Avatar asked Feb 11 '23 06:02

uncool


1 Answers

@dee provided the correct answer.

The Errorhandler: is just a place holder. It does NOT operate like you think. You are using it like an If... Then... statement:

If Error Then
   Show MsgBox
Else
    Skip MsgBox
End If

As the Errorhandler is just a placeholder and NOT an If... Then..., the code after the placeholder will run regardless of error or no error. To rectify this issue, add an Exit Sub above the Errorhandler: line:

Exit Sub

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

End Sub
like image 179
Chrismas007 Avatar answered Apr 08 '23 11:04

Chrismas007