View Single Post
  #4   Report Post  
Posted to microsoft.public.excel.programming
Patrick Molloy Patrick Molloy is offline
external usenet poster
 
Posts: 1,049
Default Error handling best practices


i addition, where you can, make assignments in functions that handle the
errors outside of your main code
, which IMHO gives better error control.
Every developer has their pet loves & hates, this is one of mu favourites.

so instead of this

Set myWS = ActiveWorkbook.Worksheets("Sheetabc")

I'd have

Set myWS = GetSheet("Sheetabc")
if myWS Is Nothing then
'handle no sheet problem here
end if


Function GetSheet(sheetname as string, optional bAdd as Boolean=False) As
Worksheet
on error resume next
SET GetSheet.Worksheets(sheetname )
if err.Number<0 then 'sheet doesn't exist
err.clear
if bAdd then
SET GetSheet.Worksheets.Add
GetSheet.Name = "Sheetabc"
end if
End If
On Error goto 0
End Function


This means that the ANTICIPATED error is handled correctly by your code and
the main routine's error handler can be left to look after unanticipated
issues.

"Barb Reinhardt" wrote in message
...
I'd like to get some ideas on error handling best practices. I prefer
to
handle the errors where they occur using something like this

Set myWS = Nothing
on error resume next
Set myWS = ActiveWorkbook.Worksheets("Sheetabc")
On Error goto 0
if not myWS is nothing then
'Do Stuff
end if

I've also seen On Error GoTo ErrHandler with the error handler at the end.
I've been trying to update a workbook that has the latter and I'm finding
it's a pain to find the errors without making other code changes. Ideas
folks?

Thanks,
Barb Reinhardt