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

  1. Dim Doc1, Doc2, oWord, oCompared
  2. Doc1= "C:\Test1.doc"
  3. Doc2= "C:\Test2.doc"
  4.  
  5. set oWord = createobject("Word.Application")
  6. oWord.Visible = true
  7.  
  8. set oCompared = oWord.Documents.Open(Doc2)
  9. oCompared.Compare(Doc1)
  10. 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.

  1. Dim oWord, Doc, currentDocument
  2. Doc = "C:\Test1.docx"
  3. Set oWord = CreateObject("Word.Application")
  4. oWord.DisplayAlerts = 0
  5. oWord.Documents.Open Doc
  6. Set currentDocument = oWord.Documents(1)
  7.  
  8. Dim nWords, n
  9. nWords = currentDocument.Words.count
  10. Print  "Number of Words: " & nWords
  11.  
  12. For n = 1 to nWords
  13. Print currentDocument.Words(n)
  14. Next
  15. currentDocument.Close
  16. Set currentDocument = Nothing
  17. oWord.Quit
  18. 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

  1. ConvertDOCtoHTMLPDF("C:\Test1.docx","Pdf")
  2. ConvertDOCtoHTMLPDF("C:\Test1.docx","html")
  3.  
  4. Function ConvertDOCtoHTMLPDF(SrcFile, Format)
  5. Dim fso, oFile, FilePath, myFile
  6. Set fso = CreateObject( "Scripting.FileSystemObject")
  7. Set oFile = fso.GetFile(SrcFile)
  8. FilePath = oFile.Path
  9.  
  10. Dim oWord
  11. Set oWord = CreateObject("Word.Application")
  12. oWord.Documents.Open FilePath
  13. If ucase(Format) = "PDF" Then
  14. myFile = fso.BuildPath (ofile.ParentFolder ,fso.GetBaseName(ofile) & ".pdf")
  15. oWord.Activedocument.Saveas myfile, 17
  16. elseIf ucase(Format) = "HTML" Then
  17. myFile = fso.BuildPath (ofile.ParentFolder ,fso.GetBaseName(ofile) & ".html")
  18. oWord.Activedocument.Saveas myfile, 8
  19. End If
  20. oWord.Quit
  21. Set oWord = Nothing
  22. Set fso = Nothing
  23. Set oFile = Nothing
  24. End Function