We have already learned the basics of automating word documents with QTP in the previous parts(Part 1, Part 2) of this series, using which you can achieve your required tasks easily. In this part, I would like to give some common examples that can be used as per the requirement.

Compare two Word documents

Dim Doc1, Doc2, oWord, oCompared
Doc1= "C:\Test1.doc"
Doc2= "C:\Test2.doc"

set oWord = createobject("Word.Application")
oWord.Visible = true

set oCompared = oWord.Documents.Open(Doc2)
oCompared.Compare(Doc1)
oCompared.Close

Above example uses word’s in built feature of comparing documents.

Extract all words from  Word document

Below example demonstrates to extract all the words from a word document also retrieves the number of words in the document.

Dim oWord, Doc, currentDocument
Doc = "C:\Test1.docx"
Set oWord = CreateObject("Word.Application")
oWord.DisplayAlerts = 0
oWord.Documents.Open Doc
Set currentDocument = oWord.Documents(1)

Dim nWords, n
nWords = currentDocument.Words.count
Print  "Number of Words: " & nWords

For n = 1 to nWords
Print currentDocument.Words(n)
Next
currentDocument.Close
Set currentDocument = Nothing
oWord.Quit
Set oWord = Nothing

Convert Word document to html/pdf

Following function can be used to convert a word document to pdf or excel. Required file will be created in the same folder of the word document file

ConvertDOCtoHTMLPDF("C:\Test1.docx","Pdf")
ConvertDOCtoHTMLPDF("C:\Test1.docx","html")

Function ConvertDOCtoHTMLPDF(SrcFile, Format)
Dim fso, oFile, FilePath, myFile
Set fso = CreateObject( "Scripting.FileSystemObject")
Set oFile = fso.GetFile(SrcFile)
FilePath = oFile.Path

Dim oWord
Set oWord = CreateObject("Word.Application")
oWord.Documents.Open FilePath
If ucase(Format) = "PDF" Then
myFile = fso.BuildPath (ofile.ParentFolder ,fso.GetBaseName(ofile) & ".pdf")
oWord.Activedocument.Saveas myfile, 17
elseIf ucase(Format) = "HTML" Then
myFile = fso.BuildPath (ofile.ParentFolder ,fso.GetBaseName(ofile) & ".html")
oWord.Activedocument.Saveas myfile, 8
End If
oWord.Quit
Set oWord = Nothing
Set fso = Nothing
Set oFile = Nothing
End Function