Friday, January 2, 2009

QTP Script 22 - How to search for a particular string in MS word document?

'For this particular script I have a word document saved in C drive with some paragraphs of text and I am searching for word 'qtp' in that word file. The search is case insensitive. I ran it using MS Word 2003.

Dim word_app
Dim word_doc
Dim str_to_search

'Create the Word Object
Set word_app = CreateObject("Word.Application")
Set word_doc = word_app.Documents.Open("C:\wrd.doc")
str_to_search = "QTP"

For p = 1 To word_doc.Paragraphs.Count

'A Range object represents a contiguous area in a document, defined by a starting character position and an ending character position. The contiguous area can be as small as the insertion point or as large as the entire document. It can also be, but does not have to be, the area represented by the current selection.

'When you use the Range method to specify a specific area of a document, you use the method's Start argument to specify the character position where the range should begin and you use the End argument to specify where the range should end.

'Using the Start and End properties with a Range object, you can create a new Range object that refers to a group of document elements.
startext_range = word_doc.Paragraphs(p).Range.Start
endRange = word_doc.Paragraphs(p).Range.End

Set text_range = word_doc.Range(startext_range, endRange)
text_range.Find.Text = str_to_search

'Performs a search based on the options set for the Find object.
text_range.Find.Execute

If text_range.Find.Found Then
msgbox str_to_search & " is found"
End If
Next
'close the document
word_doc.Close
'close the Word application
word_app.Quit
Set word_doc = Nothing
Set word_app = Nothing

Also see Word Object Model Overview here