Search here for all the info you want in this Blog

How to search for a specific string in a Microsoft Word document


You can refer to the Microsoft Word 2000 Visual Basic Reference for a complete listing of Word methods and properties that can be used within a QuickTest Professional (QTP) script. You can use these Word object methods within a QTP script to create documents, edit documents, spell check, etc.

The following example uses Word object methods to open a Microsoft Word Document and to use the Find object (the Find and Replace functionality) to search for the word "apple."

Example:
Dim wrdApp
Dim wrdDoc
Dim tString, tRange
Dim p, startRange, endRange
Dim searchString

'Create the Word Object
Set wrdApp = CreateObject("Word.Application")
Set wrdDoc = wrdApp.Documents.Open("C:\Temp\SampleWord.doc") 'replace the file with your MSDoc
searchString = "apple" 'replace this with the text you're searching for

With wrdDoc
   For p = 1 To .Paragraphs.Count
      startRange = .Paragraphs(p).Range.Start
      endRange = .Paragraphs(p).Range.End
      Set tRange = .Range(startRange, endRange)
      ' tString = tRange.Text
      tRange.Find.Text = searchString
      tRange.Find.Execute

      If tRange.Find.Found Then
         msgbox "Yes! " & searchString & " is present"
      End If

   Next
   .Close ' close the document
End With
wrdApp.Quit ' close the Word application
Set wrdDoc = Nothing
Set wrdApp = Nothing

The following example uses Word object methods to open a Microsoft Word Document and retrieve paragraphs from it. Then the InStr VBScript method is used to check for the word "apple."

Example:
Dim wrdApp
Dim wrdDoc
Dim tString, tRange
Dim p, startRange, endRange
Dim searchString

Create the Word Object
Set wrdApp = CreateObject("Word.Application")
Set wrdDoc = wrdApp.Documents.Open("C:\Temp\Text.doc") 'replace the file with your MSDoc
searchString = "apple" 'replace this with the text you're searching for

With wrdDoc
   For p = 1 To .Paragraphs.Count
      startRange = .Paragraphs(p).Range.Start
      endRange = .Paragraphs(p).Range.End
      Set tRange = .Range(startRange, endRange)
      tString = tRange.Text
      tString = Left(tString, Len(tString) - 1) 'exclude the paragraph-mark
      If InStr(1, tString, searchString) > 0 Then ' check if the text has the content you want
         ' some other processing here
         msgbox "Yes! " & searchString & " is present"
      End If
   Next
   .Close ' close the document
End With
wrdApp.Quit ' close the Word application
Set wrdDoc = Nothing
Set wrdApp = Nothing

No comments:

Post a Comment