dasanb
dasanb

Reputation: 33

EXCEL VBA: Ignore word document errors and read content

I am writing VBA code to read the word document content and paste them in excel sheets, everything is fine,

but while reading multiple word documents Some of the word document shows the error messages for example "Word could not fire an event", due to this the program hangs up.

Can anyone suggest a VBA code to ignore these type of error and read the word content.

I have my placed code below.

Dim oDoc As Word.Document
Set oDoc = GetObject("D:\176013(1).doc")
str = oDoc.Content.text 
MsgBox (str)
oDoc.Close (0)

Based on the answers

Dim wdApp As Word.Application
Dim oDoc As Word.Document
Set wdApp = CreateObject("word.Application")
wdApp.DisplayAlerts = **** 'unable to give false here, it shows only three options wdAlertsNone, wdAlertsMessageBox, wdAlertsAll
Set oDoc = wdApp.Documents.Open("D:\176013(1).doc")
str = oDoc.Content.text
oDoc.Close (0)
wdApp.Quit False

Upvotes: 1

Views: 2259

Answers (1)

EngJon
EngJon

Reputation: 997

Try

Application.DisplayAlerts = False

If you use other application objects, you have to set DisplayAlerts = False on that object.

Dim app As Word.Application
Set app = CreateObject("Word.Application")
Dim oDoc As Word.Document
app.DisplayAlerts = wdAlertsNone
On Error Resume Next
Set oDoc = app.Documents.Open("D:\176013(1).doc")
On Error GoTo 0
str = oDoc.Content.text 
MsgBox (str)
oDoc.Close (0)
app.Quit

Note: The On Error Resume Next statement is risky. It expects you to know the skipped error. If the error corrupts the document, you may not be able to read the contents of this document (in the next line), but the statement On Error GoTo 0 resets the error handling to default, so if you get an error in that line, the error will be shown.

Upvotes: 2

Related Questions