单词 VBA 范围来自单词对象

Word VBA Range from Words Object

上下文:我正在编写一个 Word VBA 宏,它循环遍历文档中的每个单词,识别首字母缩略词,并创建一个首字母缩略词列表作为新文档。下一步是确定首字母缩略词在第一次出现时是否在括号中(意味着它可能被拼写出来)。所以,我想扩大范围,看看单词两边的字符是否为“(”和“)”。

问题:我不知道如何将单词的范围分配给一个我可以扩展的范围变量。使用 "rngWord = ActiveDocument.Words(k)"(其中 k 是计数器变量)得到错误 #91,未设置对象变量或 With 块变量。所以大概有一个方法或 属性 用于我丢失的单词。但是,根据 Microsoft 的 VBA 参考,Words 集合的成员已经是范围,所以我很困惑为什么我不能将一个分配给范围变量。

Dim intArrayCount As Integer
Dim booAcroMatchesArray As Boolean
Dim intNextAcro As Integer
Dim strAcros(1000) As String
Dim strContext(1000) As String
Dim booAcroDefined(1000) As Boolean
Dim strTestMessage As String

i = 1
booAcroMatchesArray = False
intNextAcro = 1
For k = 1 To ActiveDocument.Words.Count
    strWord = ActiveDocument.Words(k).Text
    rngWord = ActiveDocument.Words(k) //The line that's missing something
    MsgBox strWord
    rngWord.Expand Unit:=wdCharacter
    strWordPlus = rngWord
    MsgBox strWordPlus



    strWord = Trim(strWord)

    If strWord = UCase(strWord) And Len(strWord) >= 2 And IsLetter(Left(strWord, 1)) = True Then
        'MsgBox ("Word = " & strWord & " and Length = " & Len(strWord))
        For intArrayCount = 1 To 1000
            If strWord = strAcros(intArrayCount) Then booAcroMatchesArray = True
        Next intArrayCount

        'MsgBox ("Word = " & strWord & " Match = " & booAcroMatchesArray)

        If booAcroMatchesArray = False Then
            strAcros(intNextAcro) = strWord
            intNextAcro = intNextAcro + 1



        End If

        booAcroMatchesArray = False

    End If

Next k

对象变量需要使用Set赋值。而不是:

rngWord = ActiveDocument.Words(k)

使用

Set rngWord = ActiveDocument.Words(k)

这个小样本工作正常:

Sub WordRangeTest()

Dim rngWord As Range
Set rngWord = ActiveDocument.Words(1)
MsgBox (rngWord.Text)

End Sub