Library tutorials & articles
Handling Errors in VB/VBA/VBS/ASP
By Mike J, published on 16 Oct 2001
Handling basic errors
Assume you have a very simple function and you wish to add some error trapping
to it. The easiest way to go about it, is simply to include the regular calls
to provided statements in Visual Basic. Here is a little example function to
show how this would work. (Throughout this article I will reuse the same function
and simply point out the hints with working with file handling too.)
This function will, on a call statement, load the desired file as a string, using the binary method for reading files. There is a very good reason to this choice of opening a file.
In older files, previously used for main frame systems, the character chr(26) was referred to as the EOF character. Reading a file for Input as an ASCII file would then throw a fit and claim that you have reached the EOF long before the EOF of the file is really there. By using a Binary method instead, you avoid this little obstacle in reading file data.
Besides, you are no longer limited to only opening ASCII files but can in fact open any file on your file system with this function, as long it is not locked by another program by the Lock Read, Lock Write, or Lock Read Write.
Refer to the Visual Basic help files "Open Statement" for further details on this behavior.
By calling this function form a module or a form, you now have a string named GetAFile containing the full file you assigned to the call. Now this seems fairly simple enough, so what could possibly go wrong in this? Many things, for one, your file that you call for may perhaps not even exist. Now is the time you start bothering with questions like, "how do I check if a file exists?", or even "What API code will … ?". Highly technical solutions indeed, to a fairly simple problem.
The answer is… Err.Number 53
Lets break down the function step by step and look at the possible errors you could get.
To make a bad story less long and very simple, "Murphy's law" always apply and remember one thing in this. The computer will do exactly what you tell it to do. If it does something wrong, it is normally caused by your failing to provide proper instructions to it.
So how do we attempt to avoid all these little errors and glitches in a previously so simple and flawless code?
Lets break it down to a better version ad remove those warning comments.
As you see from this code, there is no direct definition to the source code to handle errors in any different way, it simply does what the run time files would do by it self anyway.
In order to refine the entire error handling somewhat more, you would have to include a more elaborate way of calling different error numbers to the screen by the use of a Select Case statement.
To demonstrate this I will only re-type the source code for the ErrHandler named range instead of the entire function. (It is a wild guess from my side but I think you have the hang of how to open a file in binary mode by now.)
This function will, on a call statement, load the desired file as a string, using the binary method for reading files. There is a very good reason to this choice of opening a file.
In older files, previously used for main frame systems, the character chr(26) was referred to as the EOF character. Reading a file for Input as an ASCII file would then throw a fit and claim that you have reached the EOF long before the EOF of the file is really there. By using a Binary method instead, you avoid this little obstacle in reading file data.
Besides, you are no longer limited to only opening ASCII files but can in fact open any file on your file system with this function, as long it is not locked by another program by the Lock Read, Lock Write, or Lock Read Write.
Refer to the Visual Basic help files "Open Statement" for further details on this behavior.
Public Function GetAFile(ByRef TheFile As String) As String
Dim F As Integer
' get a free file number (always in the range 1 - 255)
F = FreeFile
'open the file in binary mode
Open TheFile For Binary As #F
'retrieve the Length Of File (file number) number of characters
'from file number F
GetAFile = Input(LOF(F), #F)
' close the file when your done
Close #F
End Function
By calling this function form a module or a form, you now have a string named GetAFile containing the full file you assigned to the call. Now this seems fairly simple enough, so what could possibly go wrong in this? Many things, for one, your file that you call for may perhaps not even exist. Now is the time you start bothering with questions like, "how do I check if a file exists?", or even "What API code will … ?". Highly technical solutions indeed, to a fairly simple problem.
The answer is… Err.Number 53
Lets break down the function step by step and look at the possible errors you could get.
Public Function GetAFile(ByRef TheFile As String) As String
Dim F As Integer
' by not assigning F a FreeFile number you will receive error 52
' bad file name or number
' get a free file number (always in the range 1 - 255)
F = FreeFile
' by assigning TheFile a file name and path that doesn’t exists
' you will receive error 53 The file not found
''it could also be error 68, 70, 71, 75 or 76.
' also attempting to open a binary file in Input mode can
' throw an error 54 Bad file mode
'( you can't open binary contents in ASCII modes)
'open the file in binary mode
Open TheFile For Binary As #F
'By using the LOF function in a closed state you also receive error
'LOF and LOC functions only work on open files. Use FileLen(TheFile)
'if you wish to see the size in bytes of a file before it is open.
'LOF and FileLen returns LONG values
GetAFile = Input(LOF(F), #F)
'forgetting to close and re-assign a new value to F may throw a fit as well
' look at error number 55 File already open as one risk.
Close #F ' close the file when your done
End Function
To make a bad story less long and very simple, "Murphy's law" always apply and remember one thing in this. The computer will do exactly what you tell it to do. If it does something wrong, it is normally caused by your failing to provide proper instructions to it.
So how do we attempt to avoid all these little errors and glitches in a previously so simple and flawless code?
Lets break it down to a better version ad remove those warning comments.
Public Function GetAFile(ByRef TheFile As String) As String
' if something goes wrong send the function
' to my named range ErrHandler
On Error GoTo ErrHandler
Dim F As Integer
F = FreeFile ' get a free file number (always in the range 1 - 255)
Open TheFile For Binary As #F 'open the file in binary mode
GetAFile = Input(LOF(F), #F)
Close #F ' close the file when your done
Exit Function ' if there was no error, don’t step further than here
ErrHandler: ' this is a named range called ErrHandler
' If there was an error raised by the function we would wind up in here 'so display
a message to the user to show what went wrong
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…
' … this resumes in the last known position.
' in this case, since its not more than a file opening occurring,
' it will simply exit the function for you.
Resume Next
End Function
As you see from this code, there is no direct definition to the source code to handle errors in any different way, it simply does what the run time files would do by it self anyway.
In order to refine the entire error handling somewhat more, you would have to include a more elaborate way of calling different error numbers to the screen by the use of a Select Case statement.
To demonstrate this I will only re-type the source code for the ErrHandler named range instead of the entire function. (It is a wild guess from my side but I think you have the hang of how to open a file in binary mode by now.)
Related articles
Related discussion
-
VB6 system conversion using VBA to Word 2007
by b.macgregor@vodamail.co.za (0 replies)
-
How to open .bat application from excel VBA or VB6
by NaseemAhmed (0 replies)
-
Outlook VBA query
by James Crowley (1 replies)
-
How to control IE from VBA
by NaseemAhmed (0 replies)
-
Run-time error '91'
by converter2009 (1 replies)
Related podcasts
-
Christian Beauclair
14 mai 2008 (�mission #0074) ::.Christian Beauclair: Stratégies de migration VB6 vers .NET Nous discutons avec Christian Beauclair des stratégies de migration VB6 vers .NET. Entre autres, nous discutons comment utiliser le "VB 6 Code Advisor" et le "Interop Forms Toolkit" pour ajouter la puiss...
Is there any way to handle errors in INFINITE LOOP.
for example,
While Not blnIdeaFound
blnIdeaFound = ProcessDetector(EXE_NAME, False)
Wend
IF THE CONTROL IS INSIDE THE LOOP ( INFINITE LOOP ), IS IT POSSIBLE TO HANDLE THIS CASE WITH A ERROR HANDLER ?
This thread is for discussions of Handling Errors in VB/VBA/VBS/ASP.