VBA Excel Error Handling - especially in functions - Professional Excel Development Style

后端 未结 3 560
盖世英雄少女心
盖世英雄少女心 2020-12-28 22:26

I got the book \"Professional Excel Development\" by Rob Bovey and it is opening up my eyes.

I am refitting my code with error handling. However, there is a lot I do

3条回答
  •  被撕碎了的回忆
    2020-12-28 22:55

    I needed a bit more help on this specific technique so I went right to the source and Mr. Bovey was gracious enough to reply. He gave me permission to post his response to the StackOverflow community.

    The instructions below refer to his preferred method of error handling for functions the "boolean error handling" technique and not to the alternate "rethrow method", both described in his book "Professional Excel Development" 2nd edition.


    Hi Shari,

    In answer to your questions about error handling in functions, there are three error handling scenarios you can have with a function in VBA:

    1) The function is so trivial that is doesn't need an error handler. In the unlikely event an error occurs in a function like this it will spill over into the error handler of the calling procedure.

    2) A non-trivial function needs an error handler and uses the Boolean return value system described in the book. Any other values the function needs to return are returned through ByRef arguments. This case covers the vast majority of functions I write. There are some things you can't do with functions like this, feeding them directly into the argument of another function is one example, but I consider this a good tradeoff in order to achieve bullet proof error handling.

    3) A non-trivial function needs an error handler and must return a value not related to its error status. This is a rare situation because I can convert 99% plus of these into case 2 by restructuring my code. If you can't do this, your only choice is to select an arbitrary return value that is out of the range of normal return values and use this to indicate that an error has occurred. If the caller of this function sees this arbitrary error flag value it knows it can't continue.

    Rob Bovey Application Professionals http://www.appspro.com/


    Code Example (Shari W)


    ' Show how to call a function using this error handling method.
    Const giBAD_RESULT As Integer = -1
    
    Function TestMath()   ' An Entry Point
    
        Dim sngResult As Single
        Dim iNum As Integer
    
        ' Call the function, actual result goes in sngResult but it returns the error handling boolean.
        ' A true error like Div 0 will go to error handler.
    
        ' Set Up Error Handling for Entry Point
        Application.EnableCancelKey = xlErrorHandler
        Dim bUserCancel As Boolean
        Const sSOURCE As String = "TestMath()"
        On Error GoTo ErrorHandler
        ' End Error Set Up
    
        iNum = 0   ' Try 0 to create error
        If Not bDoSomeMath(iNum, sngResult) Then ERR.Raise glHANDLED_ERROR
        ' If function does parameter checking and wants to return a bad input code, check for that.
        If sngResult = giBAD_RESULT Then
            MsgBox ("Bad input to bDoSomeMath " & iNum)
        Else
            MsgBox ("I believe the answer is " & sngResult)
        End If
    
    ErrorExit:
        On Error Resume Next
        Exit Function
    
    ErrorHandler:
        If bCentralErrorHandler(msMODULE, sSOURCE, , True) Then
            Stop
            Resume
        Else
            Resume ErrorExit
        End If
    End Function
    Function bDoSomeMath(ByVal iNum As Integer, ByRef sngResult As Single) As Boolean
    
        ' Error handling Set Up
        Dim bReturn As Boolean
        Const sSOURCE As String = "bDoSomeMath()"
        On Error GoTo ErrorHandler
        bReturn = True
        ' End Error Set Up
    
        If iNum < 0 Or iNum > 1000 Then
            sngResult = giBAD_RESULT   'function failed because I only like the numbers 0 to 1000
            GoTo ErrorExit
        Else
            sngResult = 100 / iNum   ' generate a true error by iNum = 0
        End If
    
    ErrorExit:
        On Error Resume Next
        bDoSomeMath = bReturn
        Exit Function
    
    ErrorHandler:
        bReturn = False
        If bCentralErrorHandler(msMODULE, sSOURCE, , , True) Then
            Stop
            Resume
        Else
            Resume ErrorExit
        End If
    
    End Function
    

提交回复
热议问题