On Error GoTo语句仍在执行,虽然没有生成错误

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

在没有任何error handling程序的情况下运行代码不会生成任何错误,但是当包含error handling语句时,仍然会显示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...占位符后面的代码将运行而不pipe错误或没有错误 。 要纠正这个问题,请在Errorhandler:上面添加一个Exit Sub Errorhandler:行:

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

在这段代码中, ErrorHandler:就是所谓的线标签 。

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

行标签不是可执行代码,而只是一个标记,可以告诉其他代码通过任何 GoTo语句跳转到哪里。 有了这些知识,他们显然不是排外的error handling程序。

这里的解决scheme是使用Exit语句从Sub “early”返回。

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

其他人可能会不同意我,但我喜欢build立我的error handling,以便代码总是停止执行Exit Sub 。 如果代码在End SubEnd Sub执行,则出现了问题。