vba - On Error 尽管没有生成错误,但 GoTo 语句仍在执行

标签 vba excel error-handling goto

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

在没有任何错误处理程序的情况下运行代码不会生成任何错误,但仍然是 msgboxErrorhandler当我包含错误处理语句时出现!

代码

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

关于vba - On Error 尽管没有生成错误,但 GoTo 语句仍在执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27708225/

相关文章:

excel - 寻找一种使用可变范围自动填充的方法

vba - 不保存宏

excel - 从 excel 粘贴到 powerpoint 时 VBA 中的运行时错误

vba - 复制或移动包含表格的一组工作表

excel - 如何找到 X 轴上具有不同时间戳的两个 Excel 数据系列之间的差异?

c - 处理错误,无限循环

c - 使用指针打印二维数组时出错

vba - 我应该如何声明这些功能?

excel - 如何在 VBA Excel 中正确使用通配符字符列表

java - 将字符串转换为 double 时在Java中进行错误检查