In this article, we will discuss how to manipulate microsoft word document using QTP and VBScript. Learning working with microsoft word can help the users to generate reports of test results in word document . We will discuss on code for following problems in this article
a. Creating a new Word document using vbscript in QTP
b. Opening an existing word document
c. Appending at the beginning and end of a word document.
d. Reading content of a word document.
e. Formatting text of a word document.
We will discuss on capturing images and working with table in MS word using vbscript in some another article:
' Instantiate an object of word application
Set objWord = CreateObject("Word.Application")
' Add a new item of word application object
objWord.Documents.Add
' Adding some text in the word document
objWord.Selection.TypeText "testing time"
' Save the document as provided
objWord.ActiveDocument.SaveAs "C:\qtptesting.docx"
' Close instance of word application
objWord.Quit
' Release the object for word document.
Set objWord=Nothing
' Instantiate an object of word application
Set objWord = CreateObject("Word.Application")
' Open an existing word document
objWord.Documents.open "C:\qtptesting.docx"
' Adding some text in the word document
objWord.Selection.TypeText "testing time 2"
' Save the document as provided
objWord.ActiveDocument.Save
' Close instance of word application
objWord.Quit
'Release the object for word document.
Set objWord=Nothing
Set objWord = CreateObject("Word.Application")
objWord.Documents.open "C:\qtptesting.docx"
' Adding some text in the word document at the end of document:
objWord.Selection.EndKey 6,0
objWord.Selection.TypeText vbCrLf & "testing time 3"
objWord.ActiveDocument.Save
' Close instance of word application
objWord.Quit
'Release the object for word document.
Set objWord=Nothing
Set objWord = CreateObject("Word.Application")
objWord.Documents.open "C:\qtptesting.docx"
' Adding formatting to the object, there will be lot of method to format , can refer to reference vbscript in QTP or word.
objWord.Selection.Font.Size ="18"
objWord.Selection.Font.Name ="18"
objWord.Selection.Font.bold = true
objWord.Selection.EndKey 6,0
' formatting changes in the code completes
objWord.Selection.TypeText vbCrLf & "testing time 3"
objWord.ActiveDocument.Save
' Close instance of word application
objWord.Quit
' Release the object for word document.
Set objWord=Nothing
Set objWord = CreateObject("Word.Application")
objWord.Documents.open "C:\qtptesting.docx"
set objdoc = objWord.Activedocument
strWordtext = ""
' read the number of words in the document and loop through the number of characters
iWordCnt= objdoc.Words.count
For i = 1 to iWordCnt
strWordtext = strWordtext + objdoc.Words(i)
Next
msgbox strWordtext
' specific changes in the code completes
objWord.Quit
'Release the object for word document.
Set objWord=Nothing