Word Index

I

Ian B

I have a range object (which is actually a field). I find
a certain word within that range and want to know what
the index of that word is, preferably within the range
although probably within the active document would be
OK. ie is it the 4th word, 10th word.

Any help much appreciated.

Ian Bayly
 
V

Vince

Not so well written but will give you an idea.

Vince

Dim a As Range ' Your range
Dim Pos As Integer ' For the index of the word
Dim Count As Integer 'Used to calc the no of spaces
Dim NoSpace As Integer ' Number of spaces in the range before the word
Dim WordToSearch As String 'What you wish to find in the range

Set a = ActiveDocument.Range ' Change this to your range
NoSpace = 0 ' Number of initial spaces set to 0

WordToSearch = "Bye"

Pos = InStr(a.text, WordToSearch) ' The index of the word 'bye' in the range
Count = 1

While InStr(Count, Mid(a.text, 1, Pos), " ") <> 0 ' calculates number of
spaces before
Count = InStr(Count, a.text, " ") + 1
NoSpace = NoSpace + 1
Wend

MsgBox WordToSearch & " is the " & Pos & "th character in the range and the
" & NoSpace + 1 & "th word in the range"
 
C

Chuck

How's this?

Dim strWord As String
Dim rngRange As Range
Dim rngBefore As Range
Dim rngWord As Range

Set rngRange = Selection.Range
Set rngWord = Selection.Range
Set rngBefore = Selection.Range

strString = "YourWord"

With rngWord.Find
.Text = strString
.Execute
If .Found = True Then
With rngBefore
.Start = rngRange.Start
.End = rngWord.Start
MsgBox strString & " is the " & _
.Words.Count + 1 & _
"th word in the range"
End With
Else
MsgBox strString & " not found"
End If
End With
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top