Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Getting index of a word or sentence in Word document

Status
Not open for further replies.

talhamoin

IS-IT--Management
Mar 3, 2011
14
AE
How can I get index of a word or sentence when using Document.Words.

Consider the following code snippet:

Code:
UserSelection = InputBox("Enter a word")
For Each LookupWord in Document.Words

Next

The code will run on below paragraph.
A quick brown fox jumps over a lazy dog. The dog was sitting beside the tree and the tree was on the bank of a river.

If the user enters "sitting", a MsgBox should show the index of word "sitting" and the sentence in which the word "sitting" appears.

Please help.
 


hi,
Code:
Dim iP As Integer, iW As Integer, pgh As Paragraph
userselection = InputBox("Enter a word")

iP = 1
For Each pgh In ThisDocument.Paragraphs
iW = 1
For Each LookupWord In pgh.Range.Words
  With LookupWord
     If Trim(.Text) = userselection Then
       MsgBox "pgh: " & iP & " wd: " & iW & " " & .Text
     End If
  End With
  iW = iW + 1
Next
iP = iP + 1
Next


Skip,
[sub]
[glasses]Just traded in my old subtlety...
for a NUANCE![tongue][/sub]
 
Hi talhamoin,

Try the following. It takes strings as well as single words and returns the count, relative position in the string and the sentence text.
Code:
Sub StringCounter()
Dim RngFnd As Range, StrFnd As String, i As Long
Dim StrLoc As String, StrMsg As String
StrFnd = InputBox("Input a string", "String Stats")
With Selection
  Set RngFnd = .Range
  .Start = .Start - 1
  With .Find
    .ClearFormatting
    .Text = StrFnd
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindStop
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
    .Execute
  End With
  Do While .Find.Found
    If .Start > RngFnd.End Then Exit Do
    i = i + 1
    With ActiveDocument.Range(RngFnd.Start, .Start)
      StrLoc = StrLoc & vbCr & i
      StrLoc = StrLoc & vbTab & .ComputeStatistics(wdStatisticWords)
      StrLoc = StrLoc & vbTab & "  " & .Sentences.Last.Text
    End With
    .Collapse wdCollapseEnd
    .Find.Execute
  Loop
End With
If StrLoc = "" Then
  StrMsg = StrFnd & " not found."
Else
  StrMsg = i & " instance(s) of " & StrFnd & " found, at:" & _
    vbCr & vbCr & "Count | Word Offset | Text" & StrLoc
End If
RngFnd.Select
MsgBox StrMsg
Set RngFnd = Nothing
End Sub

Cheers
Paul Edstein
[MS MVP - Word]
 
Thanks SkipVought

Thanks macropod. Your solution did work.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top