Jay,
Thank you for your helpful suggestions. I used them to make a few modifications to my code. Here is what it looks like at this point:
Dim CharObj As Word.Range
Dim MainStory As Word.Range
Dim PgfObj As Word.Paragraph
Dim PgfRange As Word.Range
Dim TextChar As String
Dim TextStr as String
Set MainStory = ActiveDocument.Content
With MainStory
For Each PgfObj In .Paragraphs
With PgfObj
Set PgfRange = ActiveDocument.Range(Start:=.Range.Start, End:=.Range.End)
With PgfRange
For Each CharObj In .Characters
With CharObj
TextChar = .Text
If TextChar <> Chr(13) And TextChar <> Chr(10) Then _
TextStr = TextStr & TextChar
End With
Next CharObj
End With
End With
Next PgfObj
End With
Set CharObj = Nothing
Set MainStory = Nothing
Set PgfObj = Nothing
It still seems to execute rather slowly to me. On a 2 GHz Dell laptop it takes about 3 minutes to loop through a 40 KB file. Can you see anything else I could do to further optimize the code so it will run faster? Thanks!
Sincerely,
Dan
----- Jay Freedman wrote: -----
Dan said:
I have written a VB program to read Word documents using Word.Application. The problem is that it is extremely slow. My program is simply looping through the paragraphs in the main story in a sample Word document and writing them to a text file. I am running Windows XP Professional on a 2.2 GHz Dell system with Word 2000. My test file is 77 KB, of which the main story object is about half of the file size. It takes 9 minutes to loop through the 262 paragraphs and output them to a text file. Am I doing something wrong that it should take so long?
Since you don't show the code you're using now, it's a little
difficult to recommend specifics, but here are some things that may
help:
Don't use an index into the Paragraphs collection like this:
Dim i As Integer
For i = 1 To ActiveDocument.Paragraphs.Count
' do something with ActiveDocument.Paragraphs(i)
Next i
Every time you refer to ActiveDocument.Paragraphs(i), this syntax
makes Word count from 1 to i to find the right paragraph. Instead, do
something like this:
Dim aPara As Paragraph
For Each aPara in ActiveDocument.Paragraphs
' do something with aPara
Next aPara
If you're using the .Select method to select a paragraph and then
working with the Selection object, don't do that either. This forces
Word to scroll and redraw the screen, which is very slow. Instead,
work with aPara.Range -- for example, writing out aPara.Range.Text to
the text file.