Handling Errors in VB/VBA/VBS/ASP


For the sake of elaboration, lets assume we don’t really care to do anything with the file unless it really opens up, and if for some weird reason, the file is on a path which can not be found, simply disregard the file all together.

In code this would mean, if error number = 53 then skip it otherwise treat errors as they would appear in Visual Basic runtimes.

Exit Function ' if there was no error, don’t step further than here
ErrHandler: ' this is a named range called ErrHandler

Select Case Err.Number  ' trap the actual case of the number passed by the error

Case 53 ' if the Err.Number = 53 then do this…

' don’t really do anything since we didn’t care about this
' except, the function is public and does require a return value
'lets set the string to NULL so we get some result

GetAFile = ""

Err.Clear ' now destroy the error and
Exit Function   ' get out of the function

  ' I know this is redundant in here to Exit the function but for longer functions
  ' I have taken it as a principle to follow these steps not to miss it elsewhere

Case Else ' if you get any other error code do this

MsgBox "An error happened here!" & vbCrLf & _
"Error number: " & Err.Number & vbCrLf & _
"Error Description" & Err.Description & vbCrLf & _
"Error Help Context ID" & Err.HelpContext & vbCrLf & _
"Error Help File" & Err.HelpFile, vbCritical, "ERROR MESSAGE"
Err.Clear ' destroy the error and…

End Select ' end the case statement here

Resume Next
End Function

Now of course this may seem redundant at times, but it sure does come in handy at times. Simply consider those times you use a file for setting user selected options in your program. Instead of writing the data to the registry, you could use a simple text file in a specified location, check that it really exists, and if not create a first time user file.

Included in the appendix to this article, there are several useful complete small snippets, which have also been posted individually on other web sites that show some practical use of the error events in a very localized version.

You might also like...



Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“The question of whether computers can think is just like the question of whether submarines can swim.” - Edsger W. Dijkstra