excel – On Error GoTo语句仍在执行,尽管没有生成错误

我有下面的代码,奇怪的是,即使代码中没有错误,Errorhandler程序仍在执行……可能是什么问题?

在没有任何错误处理程序的情况下运行代码不会产生任何错误,但是当我包含错误处理语句时,仍然会出现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
@dee提供了正确的答案.

Errorhandler:只是一个占位符.它并不像你想象的那样运作.你正在使用它像If … Then …声明:

If Error Then
   Show MsgBox
Else
    Skip MsgBox
End If

由于Errorhandler只是一个占位符而不是If … Then …,占位符之后的代码将运行而不管错误或没有错误.要解决此问题,请在Errorhandler:行上方添加一个Exit Sub:

Exit Sub

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

End Sub
相关文章
相关标签/搜索