问题
I'm running vba in excel to read paragraphs from a word document. The code works fine, however, I'm reading 10000 paragraphs and by the time I get to the end the loop is crawling. I wanted to try reading the word doc into memory then attempting the loop to see if it speeds up. The thing is that I'm not sure how to do this. Any suggestions?
Here is what I currently have
Set wdDoc = GetObject(wdFileName)
Set myParas = wdDoc.Paragraphs
ParCount = myParas.Count
For X = 0 To ParCount ' ParCount is 10,000
With myParas(X)
pLevel = .OutlineLevel
End With
Next X
回答1:
Word doesn't know the position of each paragraph, so when using document.Paragraphs(1234)
it has to start searching from the first paragraph.
That is why For Each
would be much faster than For
:
Dim p As Word.Paragraph
For Each p in document.Paragraphs
' do stuff
Next
来源:https://stackoverflow.com/questions/41730313/vba-slows-over-time-can-i-load-my-object-into-memory-to-speed-things-up