转到块不工作VBA

Mik*_*ogg 1 error-handling excel vba excel-vba

简介:我想做一些基本的错误处理

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

- 我对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
Run Code Online (Sandbox Code Playgroud)

sha*_*esh 7

您需要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
Run Code Online (Sandbox Code Playgroud)

查看代码,您可以将其编写为

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
Run Code Online (Sandbox Code Playgroud)

在来电者的一​​边

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
Run Code Online (Sandbox Code Playgroud)

  • 确实是这样,虽然我认为代码应该是'on error goto eh`而不是`on error on goto eh:` (2认同)