Friday, January 2, 2009

QTP Script 23 - How to Find & Replace a string in MS word document?

'I ran it using MS Word 2003.

Const wdFindContinue = 1
Const wdReplaceAll = 2

Set ob_word = CreateObject("Word.Application")
Set ob_doc = ob_word.Documents.Open("C:\wrd.doc")
Set ob_selection = ob_word.Selection
ob_selection.Find.Text = "QTP"
'This is the direction we want to search. Because we created the Selection object right at the beginning of the document we want to go forward (that is, towards the end of the document). Hence we set the value of the Forward property to True.
ob_selection.Find.Forward = True
ob_selection.Find.MatchWholeWord = True
'wdFindContinue: The find operation continues when the beginning or end of the search range is reached.
ob_selection.Find.Wrap = wdFindContinue
ob_selection.Find.Format = False
ob_selection.Find.Replacement.Text = "Mercury"
'wdReplaceAll tells the script to automatically replace all instances of the word
ob_selection.Find.Execute ,,,,,,,,,,wdReplaceAll

Set ob_doc = Nothing
Set ob_doc = Nothing