【问题标题】:goto block not working VBAgoto块不工作VBA
【发布时间】:2012-09-14 05:57:51
【问题描述】:

总结:我想做一些基本的错误处理

问题:当我单步执行代码时,即使没有错误,我的“错误”块数据也会运行

-我对 VBA 中的错误处理非常陌生,不明白为什么除了我指示代码进入块之外运行错误块中的代码。提前致谢!

代码

Function getReports()

    startJournal = Sheets("Runsheet").Range("B5")
    endJournal = Sheets("Runsheet").Range("E5")

    If startJournal = 0 Or endJournal = 0 Then

        GoTo Error

    End If

    'bunch of code

Error:
    MsgBox ("Error Statement")

End Function

【问题讨论】:

  • This post 关于错误处理可能会有所帮助。

标签: vba excel error-handling


【解决方案1】:

您需要在错误标签之前使用Exit Function
即代码应该只在出错的情况下点击标签(eh),否则退出。

Function getReports() 
on error goto eh
    startJournal = Sheets("Runsheet").Range("B5")
    endJournal = Sheets("Runsheet").Range("E5")

    If startJournal = 0 Or endJournal = 0 Then

        GoTo Error

    End If

    'bunch of code

Exit Function

eh:
    MsgBox ("Error Statement")

End Function

看看你的代码,你可以写成

Function getReports(startJournal as integer, endJournal as integer) as Boolean
    If startJournal = 0 Or endJournal = 0 Then
        msgbox "startJoural or endJournal should not be 0."
        exit function  '** exiting will return default value False to the caller
    End If

    'bunch of code
getReports = True
End Function

在调用方

if getReports(Sheets("Runsheet").Range("B5"), Sheets("Runsheet").Range("E5")) then
   call faxTheReport   '** This function will be called only if getReports returns true.
end if

【讨论】:

  • 这就是大多数人处理这个问题的方式吗?
  • 这就是应该如何完成的msdn.microsoft.com/en-us/library/t2at9t47(v=vs.80).aspx +1 @shahkalpesh
  • 确实如此,虽然我认为代码应该是on error goto eh 而不是on error goto eh:
  • @MikeKellogg - 你所做的也不是真正的错误处理;从技术上讲,你正在做分支。在我看来,错误处理会调用 Err 对象。
  • @LittleBobbyTables The problem is it technically isn't error handling
【解决方案2】:

以下是我通常如何处理 VBA 代码中的错误。这是从自动化 Internet Explorer 实例(IE 变量)的类中的代码获取的。 Log 用于通知用户正在发生的事情。变量DebugUser 是一个布尔值,当我运行代码时我将其设置为true。

Public Sub MyWorkSub()

    On Error GoTo e

    Nav "http://www.somesite.com"

    DoSomeSpecialWork

    Exit Sub
e:
    If Err.Number = -2147012894 Then
        'timeout error
        Err.Clear
        Log.Add "Timed Out... Retrying"
        MyWorkSub
        Exit Sub
    ElseIf Err.Number = -2147023170 Or Err.Number = 462 Or Err.Number = 442 Then
        RecoverIE
        Log.Add "Recovered from Internet Explorer Crash."
        Resume
    ElseIf Err.Number = 91 Then
        'Page needs reloading
        Nav "http://www.somesite.com"
        Resume 'now with this error fixed, try command again
    End If

    If DebugUser Then
        Stop 'causes break so I can debug
        Resume 'go right to the error
    End If

    Err.Raise Err.Number

End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 2017-08-14
    • 2011-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多