PDA

Click to See Complete Forum and Search --> : catch a fault in VBA


andrzej
May 31st, 2005, 08:10 AM
How can I catch a fault connected with open file ( if file dosn't exist )

Workbooks.Open( .....)

Is there something like "try .... catch" as in c++ ?

thank for help

salvelinus
May 31st, 2005, 08:45 AM
In the place where you'd use Try..., put On Error GoTo errFoo (call errFoo whatever you want). Then, at the end of the code in the sub, put in a line saying Exit Sub (this prevents the error handling code that comes next from running when there are no errors).
Next line enter errFoo: (with the colon, this indicates a label). Under that, put whatever error handling code you want. You can enter Resume to go go back and try to execute the code from the line that caused the error, Resume Next to start with the line following the error causing line, or just exit the sub.

Private Sub Foo()
On Error GoTo errFoo

'code here
'code here - throws an error
'code here - start here with Resume Next

errFoo:
msgbox Err.Description
Resume Next
End Sub

westconn1
May 31st, 2005, 09:19 AM
you can use the Dir function first to see if the file exists

if not len(Dir(pathfilename)) = 0 then
open pathfilename for whatever
end if

pete