View Single Post
  #3   Report Post  
Posted to microsoft.public.excel.programming
Peter T Peter T is offline
external usenet poster
 
Posts: 5,600
Default Error handling in VBA

In your routine you don't really need an error handler as you are testing
for the anticipated causes of an error in a way that doesn't generate an
error. That said in a production enviroment everything should run under an
error handler, although not necessarily in the same routine.

Sometimes you might want to deliverately raise an error, I've amended your
interpolate routine to demonstrate, albeit a little artificially (some other
changes too in passing)

Public Function Interp2(xArr() As Double, yArr() As Double, _
x As Double) As Double
Dim i As Long

On Error GoTo errH
If ((x < xArr(LBound(xArr))) Or (x xArr(UBound(xArr)))) Then
'MsgBox "Interp2: x is out of bound"
Err.Raise 12345, , "X = " & x
Else
For i = LBound(xArr) To UBound(xArr)
If xArr(i) = x Then
Interp2 = yArr(i)
Exit For
ElseIf xArr(i) = x Then
Interp2 = yArr(i - 1) + (x - xArr(i - 1)) / _
(xArr(i) - xArr(i - 1)) * (yArr(i) - yArr(i - 1))
Exit For
End If
Next i
End If

' i = i / 0 '' < test an error
Exit Function

errH:
If Err.Number = 12345 Then
MsgBox "Interp2: x is out of bound" & vbCr & Err.Description
Else
MsgBox Err.Description
End If
End Function

Be careful to ensure you don't accidently trigger an error after 'errH',
unless you deliberately want to raise another error to be handled in the
calling routine.

Regards,
Peter T


"deltaquattro" wrote in message
...
Hi guys,

I'm not so used to the On Error statement, ssince I come from a
Fortran background where all error handling must be performed using If
Then Else constructs. Example: in this interpolation subroutine

'Returns an interpolated value of x
'doing a lookup of xarr-yarr
Public Function Interp1(xArr() As Double, yArr() As Double, X As
Double) As Double
Dim I As Long

If ((X < xArr(LBound(xArr))) Or (X xArr(UBound(xArr)))) Then
MsgBox "Interp1: x is out of bound"
Stop
Exit Function
End If

If xArr(LBound(xArr)) = X Then
Interp1 = yArr(LBound(yArr))
Exit Function
End If
'For i = LBound(xArr) To UBound(xArr)
' If xArr(i) = X Then
' Interp1 = yArr(i - 1) + (X - xArr(i - 1)) / (xArr(i) - xArr(i -
1)) * (yArr(i) - yArr(i - 1))
' Exit Function
' End If
'Next i
I = Locate(xArr, X) + 1
Interp1 = yArr(I - 1) + (X - xArr(I - 1)) / (xArr(I) - xArr(I - 1)) *
(yArr(I) - yArr(I - 1))
End Function


woudl you advise substituting the If...MsgBox combination with an On
Error statement? In general, how can I understand if it's better to
use On Error or to test for errors with If? Finally, a purely
programming style question: would you suggest to include the error
handling in the interpolation subroutine, or to move it in the caller
subroutine? Thanks,

Best Regards

deltaquattro