Accessing Word documents

DanM

New member
Joined
Apr 30, 2009
Messages
1
Programming Experience
10+
I want to open a number of RTF documents in Word 2007, one at a time, in a VB.NET program. Here is a small representative sample of my code:

Imports Word = Microsoft.Office.Interop.Word

Public Shared WordApp As Object = Nothing
Public Shared WordAppInit As Boolean = False

Public Shared Sub ExecWord()

If Not WordAppInit Then
On Error Resume Next

WordApp = GetObject(, "Word.Application")

If Err.Number = 429 Then
WordApp = CreateObject("Word.Application")
End If

WordAppInit = True
End If

End Sub

Public Shared Sub TestInit()

WordApp = Nothing
WordAppInit = False

End Sub

Public Shared Sub TestSub1()

Dim PgfRange As Word.Range
Dim WordDoc As New Word.Document

For I = 1 To NumFiles1
Call ExecWord()

WordDoc = WordApp.Documents.Open(CType(FilePath(I - 1), Object), , True, , , , , , , , , False)

DoneLoop = False
For Each PgfObj As Word.Paragraph In WordDoc.Paragraphs
PgfRange = WordDoc.Range(Start:=CInt(PgfObj.Range.Start), End:=CInt(PgfObj.Range.End))
TextStr = PgfRange.Text

If DoneLoop Then Exit For
Next PgfObj

WordDoc.Close(SaveChanges:=False)
Next I

End Sub

Public Shared Sub TestSub2()

Dim PgfRange As Word.Range
Dim WordDoc As New Word.Document

For I = 1 To NumFiles2
Call ExecWord()

WordDoc = WordApp.Documents.Open(CType(FilePath(I - 1), Object), , True, , , , , , , , , False)

For Each PgfObj As Word.Paragraph In WordDoc.Paragraphs
PgfRange = WordDoc.Range(Start:=CInt(PgfObj.Range.Start), End:=CInt(PgfObj.Range.End))
PgfStr = PgfRange.Text
Next PgfObj

WordDoc.Close(SaveChanges:=False)
Next I

End Sub

Public Shared Sub TestDone()

If WordAppInit Then
Call WordApp.Quit(False)
WordApp = Nothing
WordAppInit = False
End If

End Sub

Public Shared Sub Test

Call TestInit()

Call TestSub1()

Call TestSub2()

Call TestDone()

End Sub

Sometimes it hangs on one of the WordApp or WordDoc statements in TestSub1; sometimes it gets all the way through TestSub1 without problems but then hangs in TestSub2. Often it leaves an instance of WinWord running so that I have to kill it in Task Manager or reboot the system.

I have a feeling that there's something about the way objects behave that I'm not understanding, but if someone could point me to changes in my code that would clear up this nebulous but irritating problem, I'd be very appreciative. Thanks!
 
Back
Top