How can I set a range for Word in vba for a specific character set?

I find the start and end character in a Word paragraph, but for life I can't figure out how to set the range that includes those characters. Here is an excerpt from what I have:

Set rngTemp = w.Paragraphs(i).Range
For iCounter = 1 To rngTemp.Characters.Count
    If rngTemp.Characters(iCounter).HighlightColorIndex = wdYellow Then
        lStartPos = iCounter
        While rngTemp.Characters(iCounter).HighlightColorIndex = wdYellow
            iCounter = iCounter + 1
        Wend
        lEndPos = iCounter

      

Using the values ​​for the start and end characters, how do you set the range that contains this string? I have made several attempts, but all failed.

The instructions on Microsoft's "Working with Ranges" page have the following code:

Set rngDoc = ActiveDocument.Range(Start:=0, End:=10)

      

I don't get any errors on the first line of my sample ("Install rngTemp ..."), which seems to be very comparable to the Microsoft sample. But when I try:

Set r = w.Paragraphs(i).Range(Start:=lStartPos, End:=lEndPos)

      

I get "Compilation error: wrong number of arguments or invalid property assignment"

+3


source to share


1 answer


I thought I found the answer with this code:

 Set r = w.Range(w.Paragraphs(i).Range.Characters(lStartPos).Start, _
          w.Paragraphs(i).Range.Characters(lEndPos).End)

      

but still got an error. In the nearest window, I pasted code from each line, and numbers appeared for each. Then I modified the set statement to use the actual numbers and it worked. For some reason VBA doesn't want to let the numbers from the code above work when setting the range variable. I changed my original code (above) to this:



Set rngTemp = w.Paragraphs(i).Range

        For iCounter = 1 To rngTemp.Characters.Count
            If rngTemp.Characters(iCounter).HighlightColorIndex = wdYellow Then

                'lStartPos = iCounter
                lStartPos = w.Paragraphs(i).Range.Characters(iCounter).Start

                While rngTemp.Characters(iCounter).HighlightColorIndex = wdYellow
                    iCounter = iCounter + 1
                Wend

                'lEndPos = iCounter
                lEndPos = w.Paragraphs(i).Range.Characters(iCounter).End

                Set r = w.Range(lStartPos, lEndPos)

      

and it worked.

+2


source







All Articles