Kelly Tessena Keck
Kelly Tessena Keck

Reputation: 215

Word VBA Range from Words Object

Context: I'm writing a Word VBA macro that loops through each word in a document, identifies the acronyms, and creates an acronym list as a new document. The next step is to identify whether the acronym is in parentheses (meaning it's likely spelled out) on its first occurrence. So, I'd like to expand the range to find out whether the characters on either side of the word are "(" and ")".

Issue: I can't figure out how to assign the range of the word to a range variable that I can then expand. Using "rngWord = ActiveDocument.Words(k)" (where k is the counter variable) gets the error #91, Object Variable or With block variable not set. So presumably there's a method or property for Words that I'm missing. Based on Microsoft's VBA reference, though, the members of the Words collection are already ranges, so I'm stumped on why I can't assign one to a range variable.

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

Upvotes: 1

Views: 2560

Answers (1)

Kelly Tessena Keck
Kelly Tessena Keck

Reputation: 215

Object variables need to be assigned using Set. Instead of:

rngWord = ActiveDocument.Words(k)

use

Set rngWord = ActiveDocument.Words(k)

This small sample worked correctly:

Sub WordRangeTest()

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

End Sub

Upvotes: 1

Related Questions