PDA

View Full Version : How to send an error message if a Document Opening Fails because the file cannot be f



VinoBob
01-05-2010, 12:15 PM
Hi!

I would like to prompt the user when a file opening fails. The file to open should be located in the active documents directory

Documents.Open FileName:=ActiveDocument.Path & "\" & "MyFile.DOC"

If the document cannot be found, then VB stops with a runtime error, so i cannot do anything after this line. Is there any exception handling in VBA? Or how can i warn the user, if the opening of a file fails?

Thanks in advance!

TonyJollans
01-05-2010, 12:29 PM
Look at the Help for "On Error". It is a fairly clumsy construct but it does enable the trapping of errors.

VinoBob
01-05-2010, 01:11 PM
Nah it doesnt work in this case for some reason. Here is my code:
Dim pth As String
pth = ActiveDocument.Path & "\" & "MyFile.DOC"
Documents.Open FileName:=pth
On Error GoTo ErrorHandler
Exit Sub
ErrorHandler:
MsgBox ("The requested file cannot be opened")

I executed the code step by step, but the On error statement doesnt get the control. The execution stops at the Documents.Open method. :think:
I also tried the forms Error event handler, without success. :mkay

lucas
01-05-2010, 01:21 PM
How can it? You have your errorhandler after the document open statement?

TonyJollans
01-05-2010, 01:32 PM
As Steve says, you must set up the error trap first, so that it is in place when the statement that causes the error is executed. A fairly common approach is to use ..

On Error Resume Next
' execute the statement
' check that it worked

In this case, perhaps

On error resume next
set doc = documents.open(pth)
If pth is Nothing then
' you have an error
Else
' all is well
End If

VinoBob
01-05-2010, 01:34 PM
Thanks m8! Now it works:thumb I placed right after entering the subroutine.

lucas
01-05-2010, 01:37 PM
Note to VinoBob, from your thread in the excel help forum.

Please use Option explicit at the top of each and every module, userform, thisdocument, etc. to avoid missed errors such as undefined variables.

It is good coding practice.