vb.net: word文档迭代单词很慢

vb.net: word document iterating words very slow

我有以下代码,选择当前页面中的文本,然后继续获取每个单词(wa是单词应用对象):

    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)

在上面的部分中,我获取了当前页面的所有文本,并且想要获取每个单词的文本。 我测试的当前页面是 450 个单词。它需要 3200 毫秒,这太多了,每个单词大约需要 7 毫秒。如果我将它限制为 100 个单词,则为 160 毫秒,每个单词大约 1.6/ms。如果我限制为 50 个单词,则为 45 毫秒,每个单词不到 1 毫秒。

最初我试图从Selection对象中获取它,但是速度是一样的。

我是不是做错了什么?我该如何改进?

遍历 450 个项目的数组并仅执行一个赋值不应该花费 3.2 秒。

Looping through an array of 450 items and just doing an assignment shouldn't take 3.2 seconds.

您正在遍历 Words 集合而不是数组。如果我没记错的话,这些集合在每次访问它们的项目时都会得到 populated/evaluated。

另一种方法是使用 Word.Range 对象并将其开始点和结束点移动到下一个单词。以下是这种技术的一种实现方式。

Dim params As New Dictionary(Of String, String)
Dim count As Int32 = 0

Dim currentPageRange As Word.Range = wa.Selection.Bookmarks("\Page").Range
Dim currentWordRange As Word.Range = doc.Range((currentPageRange.Start), (currentPageRange.Start))

Dim endOfRange As Int32 = currentPageRange.End ' store this position locally to avoid the interop property get on each iteration of the while loop

While currentWordRange.Start < endOfRange
  count += 1
  currentWordRange.Expand(Word.WdUnits.wdWord) ' move end to start of next word
  params.Add(count.ToString(), currentWordRange.Text)
  currentWordRange.Collapse(Word.WdCollapseDirection.wdCollapseEnd) ' collapse to start of next word
End While

运行 此代码针对包含 655 个单词的页面大约需要 600 毫秒,而迭代 Words 集合大约需要 3100 毫秒。