Reputation: 437
I have a loop that opens word documents however there are a few that are corrupted, I can't open them manually either,
The code I'm using to open is,
Set newdoc = objWord.Documents.Open(saveFolder & Filename)
This fails with the error
"Run-time error 5792, the file appears to be corrupted".
Is it possible to tell that the file is corrupt before trying to open it?
Upvotes: 1
Views: 2042
Reputation: 4355
In VBA it is best to keep errors to well defined functions (TryFunctions) that deal with one action and return true(no error) or false(there was an error), and use a byref parameter to return the actual result.
Public Function TryOpenDoc(byVal ipPath as string, ByRef ipDoc as Word.Document) as Boolean
On Error Resume Next
set ipDoc = Application.Documents.Open(ipPath)
TryOpenDoc = Err.Number = 0
Err.Clear
End Function
This function could be then used as follows
If TryOpenDoc(saveFolder & Filename, newdoc) then
<Code to process opened document>
Else
' raise an error, do a MsgBox or debug.print a message
Debug.print "Could not open " & saveFolder & Filename"
End If
Although it is more common to use 'If Not Try....' so that you can deal with the error before continuing on the happy code path.
Upvotes: 0
Reputation: 509
your best bet here is to use error handling.
Something like
On Error GoTo skip
Set newdoc = objWord.Documents.Open(saveFolder & Filename)
On Error GoTo 0
Exit Function
skip:
Upvotes: 0
Reputation: 57683
No, but you can test it while trying to open it.
On Error Resume Next ' deactivate error reporting
Set newdoc = Nothing
Set newdoc = objWord.Documents.Open(saveFolder & Filename)
' check if trying to open it produced an error
If Err.Number = 5792 Then
Msgbox "'" & saveFolder & Filename & "' is corrupt."
Err.Clear
End If
On Error Goto 0 ' re-activate error reporting. Do not forget this!
' if an error occured during opening then newdoc is nothing
If Not newdoc Is Nothing
' do what you want to do with the opened file
Else
' do what you want to do with a corrupt file
End If
Upvotes: 2