PDA

View Full Version : [SOLVED:] Index Value of a Word in a Paragraph



heedaf
08-22-2017, 03:24 PM
Is there a way to get the index value of a word in a paragraph. Similar to


Sub test()
Dim wapp As Word.Range

Set wapp = ActiveDocument.Range

wapp.Paragraphs(1).Range.Words(4).Select 'Highlights the 4th word in the paragraph
End Sub

but in reverse? I know I can just loop through the paragraph but it just seems like there would be a way of getting the index number of the word in the paragraph.

heedaf
08-22-2017, 03:41 PM
I found the following that seems to work. Is there another way of doing it that might be better?

Sub test()
Dim oRng As Range
Dim WrdInd As String
Set oRng = Selection.Range
oRng.Expand Unit:=wdParagraph
Set oRng = ActiveDocument.Range( _
Start:=oRng.Start, _
End:=Selection.Start)
WrdInd = oRng.ComputeStatistics(wdStatisticWords) + 1
End Sub

macropod
08-22-2017, 03:48 PM
You could use:

Sub Demo()
Dim Rng As Range, i as Long
Set Rng = Selection.Range.Paragraphs.First.Range
Rng.End = Selection.Start
i = Rng.ComputeStatistics(wdStatisticWords)
End Sub

heedaf
08-22-2017, 04:03 PM
That works great! Thanks again for your help.

heedaf
08-22-2017, 05:22 PM
I have a bit of an issue. The code you gave me doesn't count non-letters (which I would expect) but
wapp.Paragraphs(1).Range.Words(4).Select counts non-letters. So if I was to use

Sub Demo()
Dim Rng As Range, i As Long
Set Rng = Selection.Range.Paragraphs.First.Range
Rng.End = Selection.Start
i = Rng.ComputeStatistics(wdStatisticWords)
Rng.Paragraphs(1).Range.Words(i).Select
End Sub it highlights the wrong word. Is there a way of doing this where either option counts the same?

macropod
08-22-2017, 06:18 PM
You could use something like:

Sub Demo()
Dim Rng As Range, i As Long, j As Long
With Selection
Set Rng = .Paragraphs.First.Range
Rng.End = .Start
i = Rng.ComputeStatistics(wdStatisticWords)
With .Paragraphs.First.Range
For j = i To .Words.Count
Rng.End = .Words(j).End
If Rng.ComputeStatistics(wdStatisticWords) = i Then
Rng.Words.Last.Select
Exit For
End If
Next
End With
End With
End Sub
but this seems like a whole lot of circumlocution for something you could achieve with a single line of code:
Selection.Words.First.Select
And then there's the question of why you're selecting anything at all, since you rarely need to do that with VBA.

heedaf
08-22-2017, 06:28 PM
"Selection" was just for ease of discussing the problem. I'm using .find of a range to get the word. I then need to get the previous 3 words in front of what is found. I'm guessing it might just be easier to just do a loop using
Rng.Paragraphs(1).Range.Words(i).text to search for the correct string. What do you think?

macropod
08-22-2017, 06:32 PM
Why don't you use Find for the entire string? If you don't know what the previous two words are, use wildcards.