word vba-如何在查找过程中获取单词的索引值

use*_*695 1 indexing vba ms-word find

是否可以在.find期间获取单词索引?我执行 .find.text 来获取单词,但我需要它的索引位置,然后将其保存在数组中。

通常,它是

    documents("doc").word(index)
Run Code Online (Sandbox Code Playgroud)

但如果我是这样的:

    dim indexarray() as long
    dim i as long
    i = 0

    with documents("doc").content.find

         .text = word

         do while .execute
            redim preserve indexarray(i)
            indexarray(i) = index
            i = i+1
         loop

    end with
Run Code Online (Sandbox Code Playgroud)

是否可以不循环地获取索引?

Kaz*_*wor 5

无法获取您选择/找到的单词数量,但根据您的需要,有一些可能的解决方法。这里我提出一个想法。

我更改了您提供的一些代码 - 请参阅里面的一些评论:

Sub Workaround()

    Dim indexarray() As Long
    Dim i As Long
    Dim Index
    i = 0

    'searching by Range object variable
    Dim DocRNG
    Set DocRNG = ActiveDocument.Content 'here change into your document object

    'start searching with reference to variable
    With DocRNG.Find

         .Text = "commodo"  'here your text to search

         Do While .Execute

            ReDim Preserve indexarray(i)

            'possible workaround!!!
            Index = ActiveDocument.Range(0, DocRNG.End).Words.Count

            indexarray(i) = Index
            i = i + 1
         Loop

    End With
End Sub
Run Code Online (Sandbox Code Playgroud)

重要的!请记住,一些字符如:逗号、点、分号等也属于Words collection, 。因此这些句子:

Nunc viverra, imperdiet enim. Fusce est; Vivamus a tellus!
Run Code Online (Sandbox Code Playgroud)

返回 13 个单词,而您可以数出其中的 9 个。但是,我尝试和测试的建议解决方法将正常工作。