单词VAP范围来自单词对象

时间:2015-06-24 14:44:20

标签: vba ms-word word-vba

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

问题:我无法弄清楚如何将单词范围分配给我可以扩展的范围变量。使用“rngWord = ActiveDocument.Words(k)”(其中k是计数器变量)获取错误#91,对象变量或With块变量未设置。因此,据推测,我缺少一种方法或属性。但是,根据微软的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

1 个答案:

答案 0 :(得分:0)

需要使用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