Blog to understand automation concepts in QTP, Selenium Webdriver and Manual Testing concepts

Showing posts with label Test Scripts. Show all posts
Showing posts with label Test Scripts. Show all posts

Code to close multiple browsers except Quality Center/ALM in UFT/QTP?

Below Code shows how to close all browsers except browser based on the title of the browser in UFT / QTP.


Function CloseAllOpenbrowsersExcept(browsertitle)
Set oBrowser = Description.Create
oBrowser("micclass").Value = "Browser"
''Get all browsers open 
Set oBrowserLst= Desktop.ChildObjects(oBrowser)
For i=0 to oBrowserLst.count-1  
'Verify the title of the browser and close the browser if it does not the title passed
'in the function
  If InStr(oBrowserLst(i).GetROProperty("title"), browsertitle) = 0 Then
    oBrowserLst(i).close  
  End If  
Next 
Set oBrowser = nothing
Set oBrowser = nothing
End Function


Similarly we can tweak the above code to close only a particular browser as shown below:


Function CloseOpenbrowserWithTitle(browsertitle)
Set oBrowser = Description.Create
oBrowser("micclass").Value = "Browser"
''Get all browsers open 
Set oBrowserLst= Desktop.ChildObjects(oBrowser)
For i=0 to oBrowserLst.count-1  
'Verify the title of the browser and close the browser if it does not the title passed
'in the function
  If InStr(oBrowserLst(i).GetROProperty("title"), browsertitle) <> 0 Then
    oBrowserLst(i).close  
  End If  
Next 
Set oBrowser = nothing
Set oBrowser = nothing
End Function


Similarly we can close all browsers by removing the condition to check for title in the above code.


Function CloseAllOpenbrowsers()
Set oBrowser = Description.Create
oBrowser("micclass").Value = "Browser"
''Get all browsers open 
Set oBrowserLst= Desktop.ChildObjects(oBrowser)
For i=0 to oBrowserLst.count-1  
'Verify the title of the browser and close the browser if it does not the title passed
'in the function
      oBrowserLst(i).close  
Next 
Set oBrowser = nothing
Set oBrowser = nothing
End Function

VBA Code- Extracting Database data into excel sheet using macro

Code to read the data from database and writing data in excel file using VB Macro and VBA.



'''' Naming the sub as auto_open will trigger the sub automatically on opening the file.
'''' We can create a sub with different name and assign macro to a control in the excel
''''file 
Sub auto_open()
'''' define the connection string to connect to the database, it can be a dsn created,
'''' or connection string to create to the database. Please refer connectionstrings.com
'''' to connect to different database using connection string.
connStr = "dsn=testthedb''
'''' Query to fetch data from the database
strGetEmployeeDetails = "select * from employee order by UserName asc;"
''''Provide reference of sheet to add data to in the current workbook. We can add a
''''sheet in excel, or refer to an external excel file/Sheet using excel.application.
''''In this example, Sheet Employee_Details exist in the current excel file
Set worksht = ThisWorkbook.Sheets("Employee_Details")
''''--------------------------
'''' Create database connection
   Set Conn = CreateObject("ADODB.Connection")
   Set rset = CreateObject("ADODB.Recordset")
   Conn.Open connStr
   rset.Open strGetEmployeeDetails, Conn, adOpenStatic

''''The recordset is stored in rset.
''''The first row of data is the column details of the query results
''''and is added in the results header

For i = 0 To rset.Fields.Count - 1
worksht.Cells(2, i + 2) = rset.Fields(i).Name
Next i

''''Copy the recorset data into excel file starting at row 3 and column 2
worksht.Cells(3, 2).CopyFromRecordset rset
rset.Close
Set rset = Nothing
ThisWorkbook.Save
Conn.Close
Set Conn = Nothing
End Sub

VBA Code: How to auto trigger operation on opening or closing an excel file

Problem : We need to perform or auto-trigger some operation while opening or closing an excel file. There may be operations required by excel user like connecting to database and auto populating the data from database  on opening the excel file and generating pivot tables and charts automatically based on database data. Similarly it can be any other event that user want to perform on opening excel file(saved in macro-enabled xlsm file format)


How to create a module in excel VBA?


Open the VBA editor by clicking Alt + F11 or go to Developer tab and click on Visual basic. Below image shows how to create a sub or function in VBA. Following are the steps for creating a sub or function in VBA:

1. Click on Developer

2. Click on Visual basic icon. (The above two steps can be achieved by clicking on Alt + F11.

3. In the workbook, add new module.

4. In the module, add sub as shown below.


Adding a sub in visual basic



How to create a sub that will be auto-triggered on opening the excel file?


Create a sub with name as auto_open as shown in the code below. Try writing a small code as shown below which will display a message box when the excel file opens.


 Sub auto_open()  
   MsgBox "Show message while opening the excel file"  
 End Sub  

How to create a sub that will be auto-triggered on closing the excel file?


Create a sub with name as auto_close as shown in the code below. Try writing a small code as shown below which will display a message box when the excel file closes.

 Sub auto_close()  
   MsgBox "Show message while closing the excel file"  
 End Sub  

Save the excel file in .xlsm format. 


How to work with Assertions in TestNG tests

     Assertions are added in TestNG to validate whether a condition is true or false and report in test results the execution state of condition. For example in selenium test for login, we provide valid username and password and login, we expect the title to be displayed correctly in the page. Assertions are used in code, where we need to validate the state of an object properties and fail the test in case expected conditions are not met.


Different type of assertions:


  • Assert.AssertEquals(Expected condition, Actual condition) – This compares the expected condition with actual condition and fails the test in case the assertion fails.Different object types can be compared using Assert.AssertEquals
 
  • Assert.AssetEquals(Expected condition, Actual condition, Message)- This compares the expected condition with actual condition and fails the test in case the assertion fails displaying the message as defined while calling the assertion.
 
  • Assert.assertFalse(Boolean condition) - Asserts that a condition is false
 
  • Assert.assertFalse(Boolean condition, String Message )- Asserts that a condition is false. If it isn't, an Assertion Error, with the given message, is thrown.

  • Assert.assertTrue(Boolean condition, String Message )- Asserts that a condition is true. Assertion fails if condition is not true and string message is displayed.

  • Assert.AssertNull(object) – Validates if a assertion is null.


There are various other assertion which we can add in TestNG test. The issue with assertion is case execution stops in case an assertion fails. So if we do not want to stop a test on failure and continue with test execution, using assert statement will not work, instead we can wrap the assert function to verify the test condition and continue with test execution. We will discuss in future article for how to use soft assertion in the test scripts.


Below code explains how to use different assert in TestNG tests.


 package testNG;  
 import java.io.File;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.ie.InternetExplorerDriver;  
 import org.testng.Assert;  
 import org.testng.annotations.BeforeTest;  
 import org.testng.annotations.Test;  
 public class assertionVal {  
      WebDriver driver;  
      @BeforeTest  
      public void setup()   
      {  
           File file = new File("D:\\selenium\\IEDriverServer.exe");  
           System.setProperty("webdriver.ie.driver", file.getAbsolutePath());       
           driver = new InternetExplorerDriver();  
      }  
      @Test  
      public void assertVal()   
      {  
           driver.navigate().to("http://qaautomationqtp.blogspot.com");  
           Assert.assertEquals("Learning Automation Concepts in QTP", driver.getTitle());  
           //Assert to compare two values and reporting a message in case validation fails  
           Assert.assertEquals("aaa", "aaa", "this is the first test and value does not match");  
           //Assert to validate a boolean condition as false   
           Assert.assertFalse(driver.getTitle().contentEquals("Learning Automation Concepts in QTP"));  
           //Assert to validate a boolean condition as true   
           Assert.assertFalse(driver.getTitle().contentEquals("Learning Automation Concepts in QTP"));  
        //Assertion to validate an object is not null.  
        Assert.assertNotNull("driver");  
      }  
 }  

Understanding Parameters in TestNG tests

Parameters can be passed to a method from testNG.xml file. In this article, we will discuss on how to Pass parameter value in the methods.


Focus Area of this article:

  • How to pass a parameter from Testng.xml file to the test method.
  • How to define default value of a parameter in a test method.
  • How to pass multiple parameters through TestNG,xml

How to pass a parameter from Testng.xml file to the test method: 


In the below code, we have defined parameter with name as "Param1". Method mailval has argument test which will accept the value as defined in TestNG.xml file.

package testNG;

import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class NewTestoptionalParameter {
@Test
@Parameters("Param1")

  public void mailval(String Test)
  {
   System.out.println(Test);
  }
}

In the testNG.xml file, we need to provide the parameter with name and a value assigned to the parameter as seen below. So if we execute this test from testNG.xml file, we will get the output as Parameter has name as param 1.

 <?xml version="1.0" encoding="UTF-8"?>  
 <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">  
 <suite name="Suite1">  
 <parameter name="Param1" value="Parameter has name as param 1" />  
 <test name="Test1">  
 <classes>  
   <class name="testNG.NewTestoptionalParameter"/>  
 </classes>  
 </test>  
 </suite>  

Let us assume scenario where we have added a parameter in the Test method, but does not define and provide the value of the parameter in the testNG.xml file as shown in the below xml file code.In this case, on execution of the test, we will get the output as blank.

 <?xml version="1.0" encoding="UTF-8"?>  
 <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">  
 <suite name="Suite1">  
 <test name="Test1">  
 <classes>  
   <class name="testNG.NewTestoptionalParameter"/>  
 </classes>  
 </test>  
 </suite>  

We can assign default value to a parameter using Optional as shown in the code below. Now in case we do not define the parameter in the TestNG.xml file, the argument will work with the assigned default value and will output in console as "testing".

package testNG;

import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class NewTestoptionalParameter {
@Test
@Parameters("Param1")

  public void mailval(@Optional("testing") String Test)
  {
   System.out.println(Test);
  }
}

Next thing, we can define multiple parameters for a method as shown in the code below:

package testNG;

import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class NewTestoptionalParameter {
@Test
@Parameters({"Param1","Param2"})

  public void mailval(@Optional("resting") String Test, String Test1)
  {
   System.out.println(Test);
  }
}

And finally , we can define the test parameter at test level as well as suite level. If a parameter is defined at both test as well as suite level, Parameter value defined at test level is considered. 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite1">
<parameter name="Param1" value="Parameter has name as param 1s" /> 
<test name="Test1">
 <parameter name="Param1" value="Parameter has name as param 1t" /> 
 <parameter name="Param2" value="Parameter has name as param 2t" /> 
<classes>
    <class name="testNG.NewTestoptionalParameter"/>
</classes>
</test>
</suite>

Creating first TestNG test using eclipse for Selenium WebDriver


TestNG provides a testing framework to test the application. TestNG framework can be used to write unit test, integration as well as functional tests. Our objective in this blog will be to understand and implement TestNG framework while automating with Selenium WebDriver using eclipse.


In the previous article, we explained how to install TestNG libraries with eclipse. In this article, we will explain how to create first TestNG test in eclipse.

Pre-Requisite: We have installed TestNG as discussed in previous article.


Steps to create first TestNG test in eclipse:

  • Create a new Project in eclipse as shown in the image below and add the TestNG library:

Add TestNG library to eclipse java Project



Add TestNG library
Add caption

  • Once we have added the library, we can use the library in our test.

Creating a testNG Class in the java Project:


A testNG test is executed based on the testNG annotations in the TestNG class.

Creating a testNG class
New TestNG class

Below code will be generated once we click on finish.


 package testNG;  
 import org.testng.annotations.Test;  
 import org.testng.annotations.BeforeTest;  
 import org.testng.annotations.AfterTest;  
 public class NewTest {  
  @Test  
  public void f() {  
  }  
  @BeforeTest  
  public void beforeTest() {  
  }  
  @AfterTest  
  public void afterTest() {  
  }  
 }  

Tips for Managing test data in QTP test scripts

Test Data management is an important factor for a robust automation framework. Test Data should be easily used by test scripts and should cover both positive and negative test scenarios.One of the key for successful automation is to avoid hard coded values and data in the test. To avoid hard coding test data in the script and running the same test script with multiple test data, we should take care of points explained in this article for using test data in the automation framework:


  • Test data should be maintained in external data source which can be an excel, csv or database.
  • Test data should be flexible. Suppose we need additional column to be used by test scripts.Test data should be used by test script in such a manner that changing the columns order or adding new column does not make any change in the test script.
  • Let me explain the above point with an example. Suppose initial excel file from which test data was read has three columns of data, Password, UserName and LoginResult. Suppose if a new column has been added for dateofBirth.  Adding this new column before Loginresult should not impact the script execution.

Password
UserName
DateofBirth
LoginResult
TEST
User1
22-06-1984
FAIL
TEST
User2
13-05-1998
FAIL
T20
T200
12-09-1908
PASS
ODI
T500
12-01-2013
FAIL


  • For this, we should have the column name in the first row as header and should use the test data from next row onward in the test script.The header fields name should be short but self explanatory. In the above example, Password, UserName, DateofBirth and LoginResult are header.
  • The test script should provide enough flexibility to execute a given row of data or not. To provide this we should use a column for Execution Flag which will indicate whether to execute the test with the test data in the row or skip to next row. Test script should be created in manner that they can be executed and iterated with multiple rows of data.
  •  Change in test data from one source to another, i.e. database to excel should have minimum impact on the test script execution.
  • We can consider using test generator tools which can generate random data for testing an application.
  • While preparing test data, we should dry run the test script with both positive and negative data to validate script behavior on both positive and negative conditions.

How to use Test data from external sources:


  • Test data can be imported from external source using import method or using excel object.
  • In case of using import methods, we will import a sheet (using import or importsheet method) or excel file into QTP data table and extract the data and use in test using get methods.
  •   In case of using Excel application, we can import the data in a two dimension array and then use data from the array or using scripting.dictionary to use data from the array.
  • Below is the algorithm of using scripting.dictionary to read the data and use in test scripts.
    • Create an array (two dimensional) for the data in the excel sheet.
    • From the array, read the top row data as header information and loop through rest of the column as data.Store the value as key-value pair e.g : Key Password will have value as ODI for the last row of the iteration. 
Below article shows how to use dictionary object to data drive a test in QTP:




How to use Dictionary object in QTP for creating data driven tests

This below code explains how to use scripting.dictionary to read data from excel object and create a dictionary from the excel. Using dictionary object, we can data drive a test and easily use the test data in test script based on dictionary Key-value pair. 


For details on scripting.dictionary object, see Dictionary Object in QTP

Below code explains how to use dictionary object for creating data driven tests using Dictionary object:

 call func_getDictionaryData("c:/test.xlsX", "Sheet1", 5)  
 Function func_getDictionaryData(strExcelFile,strsheetName, iRow)  
 On error resume next  
 'Create an instance of Excel object   
  Set objExcel = Createobject("Excel.Application")  
  objExcel.visible = false  
  ''open the workbook and the specified worksheet, These two are required as argument to the function  
  Set objExcelbook = objExcel.Workbooks.Open(strExcelFile)  
  Set objExcelsheet = objExcelbook.Worksheets(strsheetName)  
  ''Get the rows and column count of the excelsheet  
 intColCnt = objExcelsheet.UsedRange.Columns.Count  
 intRowCnt = objExcelsheet.UsedRange.Rows.Count  
 If (iRow>intRowCnt) Then  
   msgbox "Row number provided in function is greater than the rows in the sheet"  
 else  
  ''Create a dictionary object  
  Set objDictdta = Createobject("Scripting.dictionary")  
  For i=1 to intColCnt  
     dictKey = Trim(objExcelsheet.Cells(1,i))  
     dictVal = Trim(objExcelsheet.Cells(iRow,i))  
     objDictdta.Add dictKey,dictVal  
  Next  
 End If  
 objExcel.close  
 Set objExcel = nothing  
 objDictdta.close  
 Set objDictdta = nothing  
 If (err.number>0) then  
    msgbox "error in the file: "+ err.description  
 End If  
 End Function  

How to load multiple function libraries at runtime from Quality Center in QTP

This post explains how to load multiple libraries at runtime from Quality Center in a QTP test. As the test size grows, it is better to associate or load function library at runtime with all the tests. 

Note we should associate an initialization library with each of the test and then perform following work in the initialization library. 


  • Load all the function library with the test
  • Load the shared object Repository with the test.
  • Remove the local object repository with the test to avoid object conflict
  • Load the environment variables to be used across test
  • Close all instances of application.
  • Providing the reporter configuration for the test. e.g: allowing reporting in QTP Reporter on scenario of error only


In the current post, we will focus only on how to load multiple libraries at runtime from Quality Center or local folder.


In the case of using local folder structure , the path [QualityCenter] Subject\Project_Name \......   changes to c:\QTP_Automation/......

 Const strLibraryNames = "[QualityCenter] Subject\Project_Name\QTP\Libraries\Library1.vbs>[QualityCenter] Subject\Project_Name\QTP\Libraries\Library2.vbs>[QualityCenter] Subject\Project_Name\QTP\Libraries\Library3.vbs>[QualityCenter] Subject\Project_Name\QTP\Libraries\Library4.vbs"  
 callfunc_LoadFunctionLibrary(strLibraryNames)  
 Function func_LoadFunctionLibrary(strLibraryName)  
  ''Load multiple Library Files seperated by '>'  
  collLibrary = split(strLibraryName, ">")  
    ''Now collLibrary is an array with each element in array storing the path of library  
  For i = 0 to ubound(collLibrary)  
  LoadFunctionLibrary collLibrary(i)  
  Next   
 End Function  

How to create and work with Class using VBScript Code in QTP

Using Class in VBScript, we are able to create an instance of object and use properties and methods of the object. 


Points to remember with VBScript Class concept:

  • We can define variables, methods, properties, and event members in the class.
  • All the members of a class can be declared as Private or Public.
  • Members declared as Private are visible within the Class block. 
  • Members declared as Public are accessible from within and outside the class.
  • Members are by default Public. If we don't provide member as Private or Public


Syntax of Class Statement in VBScript


Class ClassName

       Statement of Code

End Class


Understanding Implementation of class in VBScript with an example


'' Here we have defined a class with name as VBSriptClass

Class VBScriptClass

''Once we have created a class, next we need to define the members of the VBScript.

''We have taken all the types of members in this example

'' A variable can be defined as Private or Public 


Private var_ClassName 
Public var_Name

''Class Events - Class_Initialize and Class_Terminate are events which we can define in a class

''We can define the action which we need to perform when we instantiate a class in the class_initialize sub as shown below.

Private sub Class_Initialize(  )
msgbox "We have initialised the test. This pop up will appear the moment new instance of class object is created"
End Sub

''When Object is Set to Nothing/destroyed, Class_Terminate event is executed and actions are performed as defined in the sub. 

Private Sub Class_Terminate(  )
msgbox "We have terminated the test. This pop up will appear the moment instance of class object is destroyed/set as nothing"
End Sub

'' Property Let and Get allows to set and extract values from properties in the class

''get method allows to extract value set for property in the class

Public Property Get ClassName
       ClassName = var_ClassName
End Property 

''Let method allows to set value for the Property

Public Property Let ClassName (strClassName) 
         var_ClassName = strClassName 
End Property 

''We can define function in the class. the below example will sum two numbers

''Only Public functions can be used in code outside of the class 

public function sum(a,b)
        sum = a+b
        addition a,b
End Function

''Private method cannot be called outside the class but can be called by another function within the class

Private function addition(a,b)
       msgbox a*b
End function

''A sub/function which is not defined as either Private/Public can be assesed outside the class and works as public method

Sub DisplayUserName 
      msgbox UserName 
End Sub 
End Class 


Using Class members outside the class code


''We can define an instance or object of class as set in below code

Set objClass = New VBScriptClass

''Once the instance of the clas is created, we can used the public members of the class as shown below.

'' Set value of the property of the method.

objClass.ClassName  = "Are we talking about Dance Classes?"
msgbox objClass.sum(12,15)
msgbox objClass.ClassName

'' Close the instance of the class object

Set objClass = nothing


How to use err object to continue test execution in VBSript and QTP


''Err object holds the information for last runtime error that occurred in the test execution


'' In the piece of code, we can add on error resume next to continue with execution . It will not abort the execution but will store the information of the error.


'' Once a new runtime error occur, in that case , the err object stores the information of new error. So handle must be taken to add reporting in test and clearing the error


''Methods for err object are err.raise and err.clear


'' On error Resume next will continue with execution. try to comment the On error resume next , and then see what happens in case on error resume next statement is not provided.


On Error Resume Next 

'' Err.raise <number> will generate err object for err number provided. At runtime as an error is encountered, err object populates the information of error. 

Err.Raise 9err_number= Err.number 

'' Using err.description, we can extract information about the error

err_description= Err.description 

'' In case no error is encountered in the execution , the err. number has number as 0. Therefore we can use If else loop based on value of err.num and report to the QTP Report.

If numerr <> 0 Then 

 ''Reporter.Reportevent ........

msgbox (numerr & " Some error in application")

Else

''Reporter.reportevent ........

End If



'' Once we have validated a piece of code, we should clear the err using err.clear

err.clear

msgbox err.number



''you will see msgbox will display value as 0 now. 



How to create array from string separated by delimiter using vbscript split function


Suppose we have a string with value as : stringA = "nitin>joshi>qa>qtp>automation"

'' We can create an array using split function


Strarray = Split(StringA, ">")
'' we can loop through the array element using:

 intPropSet = Ubound(Strarray)  ''this gives the length or upper bound index of array.

  for i = 0 to intPropSet

      msgbox strarray(i)

  Next


''This can be useful to loop in validating multiple values ''e.g : Validating existence of multiple links with name as nitin or joshi or qtp or automation


''We can combine the values in an array using join statement


If (IsArray(Strarray)) then

   stringB = Join(Strarray, ">")

   msgbox "array with text: " + stringB

Else

   msgbox "not an array"

End If


So while understanding How to create array from string separated by delimiter using vbscript split function, we have now understanding of Join, split, IsArray,Ubound and lbound also


Manipulating and working with Word document using vbscript in QTP

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: 


Example 1 - Creating a new word document using vbscript. Writing some text in the document and closing the same


' 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

Example 2 - The above was example of adding a new document in case we wish to update an existing document, we can use the below code:


' 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


Example 3 : Now we have seen the text in above example 2 writes "testing time 2" just before testingtime. Suppose we want to write the text testing 2 in a new line after text testing, we can write the code as



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

Example 4 : Next we want to format the text in the word document.


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

Example 5: Reading content of a word document and storing in a string


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