Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a range for Word in vba for a specific set of characters?

Tags:

range

ms-word

vba

I am finding a starting and ending character within a Word paragraph, but for the life of me, cannot determine how to set a range that includes those characters. Here is an excerpt of 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 starting and ending characters, how do I set a range that contains that string? I have made a number of attempts, but all unsuccessful.

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

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

I receive no errors in the first line of my sample ("Set rngTemp ..."), which seems to be very comparable to Microsoft's sample. But when I try:

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

I get the "Compile Error: Wrong number of arguments or invalid property assignment"

like image 380
RaifMT Avatar asked Oct 31 '22 13:10

RaifMT


1 Answers

I thought I had 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 it still produced an error. In the immediate window, I pasted the code from each line and the numbers showed up for each. Then I changed the set statement to use the actual numbers, and that worked. For some reason, VBA does not like to allow the numbers from the code immediately above to work in setting the range variable. I changed the original code (from the top) 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.

like image 59
RaifMT Avatar answered Nov 15 '22 07:11

RaifMT