PDA

View Full Version : [SOLVED:] Getting Word Position in a Paragraph



heedaf
10-12-2017, 12:51 PM
Is there a way of getting the position number of a selected word in a paragraph? I'm using oPara.paragraphs(1).range.words(k).text to loop through a paragraph to find the value of k for a specific word but I was hoping there was a simpler way of getting this value. Any ideas?

macropod
10-12-2017, 02:28 PM
What do you want to retrieve about the word's position, its index or its offset?

heedaf
10-12-2017, 03:03 PM
I believe index. oPara.paragraphs(1).range.words(3).text would give the 3rd word in the paragraph. So if I have a range set on a specific word in a paragraph I would like to know what "index" number it is in the paragraph.

I'm using a range.find to find a specific word in a paragraph and I need to get the first 3 words before and the 3 words after.

macropod
10-12-2017, 03:16 PM
Sub Demo()
With Selection
.Start = .Paragraphs.First.Range.Start
MsgBox .Range.ComputeStatistics(wdStatisticWords)
End With
End Sub
will tell you which grammatical word it is, whilst

Sub Demo()
With Selection
.Start = .Paragraphs.First.Range.Start
MsgBox .Words.Count
End With
End Sub
will tell you which VBA 'word' it is.

heedaf
10-12-2017, 03:23 PM
Thank you very much. Just what I was looking for.

macropod
10-12-2017, 03:36 PM
I'm using a range.find to find a specific word in a paragraph and I need to get the first 3 words before and the 3 words after.
So why not simply move the start & end without computing the index?

Sub Demo()
Application.ScreenUpdating = False
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "Text"
.Replacement.Text = ""
.Format = False
.Forward = True
.Wrap = wdFindContinue
.MatchCase = True
.MatchWholeWord = True
.MatchWildcards = False
.Execute
End With
If .Find.Found Then
.MoveStart wdWord, -6
While .ComputeStatistics(wdStatisticWords) > 4
.MoveStart wdWord, 1
Wend
.MoveEnd wdWord, 6
While .ComputeStatistics(wdStatisticWords) > 7
.MoveEnd wdWord, -1
Wend
MsgBox .Text
End If
End With
Application.ScreenUpdating = True
End Sub