I have the following code, which selects the text in the current page and then procedes to get each word (wa
is the word application object):
wa.Selection.MoveUp(Word.WdUnits.wdWindow, 1, 1) '0=move,1=extend
wa.Selection.Collapse()
wa.Selection.MoveDown(Word.WdUnits.wdWindow, 1, 1) '0=move,1=extend
Dim r As Word.Range
r = wa.Selection.FormattedText
Dim Stopwatch As New Stopwatch()
Stopwatch.Start()
Dim params = New Dictionary(Of String, String)
Dim wrd As String
For i = 1 To r.Words.Count 'wa.Selection.Words.Count
'params.Add(CStr(i), r.Words.Item(i).Text)
wrd = r.Words.Item(i).Text 'wa.Selection.Words.Item(i).Text.ToString()
Next
Stopwatch.Stop()
MsgBox(Stopwatch.Elapsed.TotalMilliseconds & "###" & wa.Selection.Words.Count)
In the above section, i get all the text of the current page and want to get each word's text.
the current page where i test is 450 words. it takes 3200 milliseconds, which is way too much, about 7ms per word. if i limit it to 100 words, it's 160 milliseconds, about 1.6/ms per word. If i limit to 50 words, it's 45 milliseconds, less than one ms per word.
Initially I was trying to get it from the Selection
object, but the speed is the same.
Am I doing something wrong? How can I improve on this?
Looping through an array of 450 items and just doing an assignment shouldn't take 3.2 seconds.
question from:
https://stackoverflow.com/questions/65599894/vb-net-word-document-iterating-words-very-slow 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…