转储Microsoft Word文本而不循环

时间:2016-03-12 16:42:33

标签: vba ms-word word-vba

有没有办法将每个单词及其起始范围和结束范围转储到数组或字典等中而不进行循环?

我已经尝试了以下两种方法,它们可以正常工作,

Sub test_1()
Dim wrd As Variant
Dim TxtArray() As String
Dim i As Long

For Each wrd In ActiveDocument.Range.Words
'code to add to add to array her
Next
End Sub

Sub test_2()
Dim TxtArray() As String
TxtArray = Split(ActiveDocument.Range.Text)
End Sub

分割方法不能给我选项来注册每个单词的起始和结束范围位置,因为我可能想稍后突出显示它们;加上当我在字典中添加单词时,我删除了重复的单词

有没有办法在没有循环的情况下转储Range.Words集合?我试过了,但它没有用。

1 个答案:

答案 0 :(得分:1)

“当我在字典中添加单词时,我会消除重复的单词” - 您不必这样做:使用范围数组作为字典的值,将单词作为键。

例如:

Sub MapWords()

    Dim d As New Scripting.Dictionary

    Dim wrd As Variant, tmp, ub As Long, txt As String, w

    Dim i As Long

    For Each wrd In ActiveDocument.Range.Words
        txt = Trim(wrd.Text)
        If Len(txt) > 1 Then
            If Not d.Exists(txt) Then
                d.Add txt, GetArray(wrd)
            Else
                tmp = d(txt)
                ub = UBound(tmp) + 1
                ReDim Preserve tmp(1 To ub)
                Set tmp(ub) = wrd
                d(txt) = tmp
            End If
        End If
    Next

    'e.g. -
    Set w = d("split")(1)
    Debug.Print w.Text, w.Start, w.End

End Sub

Function GetArray(wrd)
    Dim rv(1 To 1)
    Set rv(1) = wrd
    GetArray = rv
End Function