goto block not working VBA

2019-08-01 20:39发布

Summary: I want to do some basic error-handling

Problem: When I step through the code my "Error" block data gets run even when there isn't an error

-I'm pretty new to error handling in VBA and don't understand why the code in the Error block is run aside from me directing the code to enter the block. Thanks in Advance!

Code:

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

2条回答
我只想做你的唯一
2楼-- · 2019-08-01 20:58

Here is how I generally deal with errors in my VBA code. This was taken from code in a class that automates an instance of Internet Explorer (the IE variable). The Log is used to inform the user of what's going on. The variable DebugUser is a boolean which I set to true when I'm the one running the code.

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
查看更多
唯我独甜
3楼-- · 2019-08-01 21:19

You need Exit Function before the error label.
i.e. the code should hit the label (eh) only in case of error & exit otherwise.

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

Looking at your code, you could write it as

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

On the caller's side

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
查看更多
登录 后发表回答