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

Showing posts with label VBScript Tutorials. Show all posts
Showing posts with label VBScript Tutorials. Show all posts

VBScript code to convert Excel data to HTML format


This article explains the code to convert content of an excel file into html code. This can be useful for better representation of excel data in html format.

Code to convert Excel data to HTML format

''strWbk - Full path of the excel workbook
''strWsheetName - Name of the worksheet
'' strHTMLFile - Name of the html file with path
Public Function CreateHTMLFromExcel(strWbk,strWsheetName,strHTMLFile)
Set oExcel = Createobject("Excel.Application")
oExcel.visible = false
Set objExcelWB = oExcel.Workbooks.Open(strWbkPath)
Set objExcelWS = objExcelWB.Worksheets(strWsheetName)
'Getting the rows and column count
 strColumnCount = objExcelWS.UsedRange.Columns.Count
 strTotRows = objExcelWS.UsedRange.Rows.Count
strTable = "<table border=""""2"""">"
'Create html table based on content of the excel file
 For j=1 to strTotRows
  strTable = strTable & "<tr>"
  For i=1 to strColumnCount
    strData = Trim(objExcelWS.Cells(j,i))
    strTable= strTable & "<td>"& strData &"</td>"
  Next
  strTable =strTable & "</tr>"
 Next
 strTable = strTable & "</table>"
 set objFSO=Createobject("scripting.FileSystemObject")
 set objtxt = objFSO.createTextFile(strHTMLFile)
    objtxt.write(strTable)
'Closing the workbook
 objExcelWB.Close
 set objFSO =nothing
End Function

Renaming all/specific subfolders in a folder using vbscript FSO

In this post, how to rename all the subfolders in a folder using vbscript is explained

  • Renaming all sub folders in a folder removing spaces from the file

call RemoveblankSpace_Subfolders("D:\TextTest")

 ''strbasefoldername - Folder Path in which file needs to be replaced
 Public Function RemoveblankSpace_Subfolders(strbasefoldername)
 On error resume next
 Dim objFSO
 Set objFSO = CreateObject("Scripting.FileSystemObject") 
    Dim objFolder 
    For Each objSubFolder In objFSO.GetFolder(strbasefoldername).SubFolders
     FlderName = objSubFolder.Name
  FlderName = replace(FlderName," ","")
  objSubFolder.Name = FlderName
    Next 
    Set objSubFolderFolder = Nothing 
    Set objFSO = Nothing 
End Function

  • Rename specific subfolder in a folder using vbscript


call Rename_Subfolders("D:\TextTest","es","twist",false,"test")

'' strbasefoldername - Folder Path in which file needs to be replaced
'' strFindtext - text in the folder name that needs to be replaced
'' strReplaceText - new text to replace the existing test
'' boolAllFlders - boolean flag to indicate if all the subfolder needs to be renamed or
'' specific folders needs to be renamed
'' OnlyfoldersWithText - replace only folder with specific text. will consider only if
'' boolAllFlders =true
 Public Function Rename_Subfolders(strbasefoldername,strFindtext,strReplaceText,boolAllFlders,OnlyfoldersWithText)
 On error resume next
 Dim objFSO
 Set objFSO = CreateObject("Scripting.FileSystemObject") 
    Dim objFolder
    For Each objSubFolder In objFSO.GetFolder(strbasefoldername).SubFolders
 FlderName = objSubFolder.Name
  if boolAllFlders = false then
   if(instr(1,FlderName,OnlyfoldersWithText)>0) then
    FlderName = replace(FlderName,strFindtext,strReplaceText)
    objSubFolder.Name = FlderName
   End If
  else
    FlderName = replace(FlderName,strFindtext,strReplaceText)
    objSubFolder.Name = FlderName
  End If
    Next 
    Set objSubFolderFolder = Nothing 
    Set objFSO = Nothing 
End Function

Manipulation XML using XPath for VBScript/UFT

This article explains how to extract information from an xml file based on the element xpath using Microsoft.XMLDOM and VBSript. You can try using the code as shown below.


''---------------------------------------------------------------------------------
'' Step 1 : Copy the content removing comments in a file and save the file
''----------------------------------------------------------------------------------

'' --------------File Content ------------------------------------------------------
''XMLTextFile = "<books><name>mybook</name><price>50</price><Author rating="high">matt</Author>
''<name>his book</name><price>150</price><Author rating="low">henry</Author>
''<name>twist</name><price>550</price><Author rating="high">henry</Author></books>"

''-------------Call the functions with Parameters------------------------------------
msgbox getXMLTextFileValue("d:\testdta.xml","//price")
msgbox getXMLTextFileValue("d:\testdta.xml","//Author[@rating='high']")
msgbox getxmlAttributeValue("d:\testdta.xml","//Author","rating")
call getAllNodeValues("d:\testdta.xml","//Author")
''-----------------------------------------------------------------------------------

'' Function 1 - Reading the node text
''Arguments - FileName and xpath of node

''-----------------------------------------------------------------------------------
function getXMLTextFileValue(XMLTextFile,NodeXpath)
Set objXML = CreateObject("Microsoft.XMLDOM")

objXML.async = False
objXML.resolveExternals = False
objXML.validateOnParse = False
getXMLTextFileValue = ""
boolxmlParse = objXML.load(XMLTextFile)
if(boolxmlParse) then
 objXML.setProperty "SelectionLanguage", "XPath"
 set objXML_node = objXML.selectSingleNode(NodeXpath)
        getXMLTextFileValue = objXML_node.text
 else
 msgbox "issue in xml file"
End If
End Function

''-----------------------------------------------------------------------------------

'' Function 1 - Reading the node attribute value
''Arguments - FileName and xpath of node. attribute Name of which value is to be returned

''-----------------------------------------------------------------------------------


function getxmlAttributeValue(XMLTextFile,NodeXpath, attributeName)
Set objXML = CreateObject("Microsoft.XMLDOM")

objXML.async = False
objXML.resolveExternals = False
objXML.validateOnParse = False
getxmlAttributeValue = ""
boolxmlParse = objXML.load(XMLTextFile)
if(boolxmlParse) then
 objXML.setProperty "SelectionLanguage", "XPath"
 set objXML_node = objXML.selectSingleNode(NodeXpath)
        getxmlAttributeValue = objXML_node.getAttribute(attributeName)
 else
 msgbox "issue in xml file"
End If
End Function

''-----------------------------------------------------------------------------------

'' Function 1 - Reading the value of all the matching nodes
''Arguments - FileName and xpath of node.

''-----------------------------------------------------------------------------------

function getAllNodeValues(XMLTextFile,NodeXpath)
Set objXML = CreateObject("Microsoft.XMLDOM")

objXML.async = False
objXML.resolveExternals = False
objXML.validateOnParse = False

boolxmlParse = objXML.load(XMLTextFile)
if(boolxmlParse) then
 objXML.setProperty "SelectionLanguage", "XPath"
 set objXML_node = objXML.selectNodes(NodeXpath)
        for each nodet in objXML_node
  msgbox nodet.text
 Next
End If
End Function

Sorting excel data multiple times based on column Name using VBScript


''Input Information - Workbook file Name with path
''WorkSheet Name
'' Provide the sort criteria based on which data needs to be filtered seperated by |

WorkBookFile = "C:\\testing.xls"
SheetName = "testing"
MultipleSortCriteria = "TestName|TestClass|TestPath"
'' Define the constants to be used in the script
  Const xlYes = 1
  Const xlAscending = 1
  Const xlDescending = 2
  Set oXL = CreateObject("Excel.Application")
  Set oWB = oXL.WorkBooks.Open(WorkBookFile)
  Set oWS = oWB.Worksheets(SheetName)  
  Set oRnge = oWS.UsedRange
  ColCnt = oRnge.columns.count
  '' Create an array based on the sort criteria provided 
  aSrtCriteria = split(MultipleSortCriteria,"|")
  For i = ubound(aSrtCriteria) to 0 step -1
  ''Loop the times data needs to be sorted
   For j = 1 to ColCount step 1
    
    If (oWS.cells(1,j).value =aSrtCriteria(i)) Then
     '' Sort the data based on the column name
     Set oRngeSrt = oXL.Range(Chr(asc("A")- 1+j) & "1")
     oRnge.Sort oRngeSrt, xlDescending, , , , , , xlYes 
     oWB.save
      Exit For
    End If    
   Next
  Next
   oWB.Close
   oXL.Quit
   Set oWB = Nothing
   Set oXL = Nothing
 

VBScript Code to close the IE browsers and Internet Explorer not responding window


  • VBScript Code to close the IE browsers and Internet Explorer not responding window

Set WShell = CreateObject("WScript.Shell")
''This will close all the instances of task iexplore.exe.
''Parameter /f kills the process forcefully
WShell.Exec("taskkill /fi ""imagename eq iexplore.exe"" /f")
WScript.Sleep 100
''At time Internet explorer is not responding error is displayed
''The task has window title as internet explorer not responding.
''We can close the task based on window title with regular expression as Internet *
WShell.Exec("taskkill /fi ""WINDOWTITLE eq Internet*"" /f")
WScript.Sleep 100
''Once the window is closed, another window appear with similar title
'' which needs to be closed
WShell.Exec("taskkill /fi ""WINDOWTITLE eq Internet*"" /f")

  • VBScript Code to save the list of running tasks and save it in file abc.txt


''Below command will return the service for the process and save it in file abc.txt
  Set WShell = CreateObject("WScript.Shell")
''This will close all the instances of task iexplore.exe.
''Parameter /f kills the process forcefully
WShell.Exec("tasklist /fi /svc>test.txt")

Tutorial about Array in VBScript for QTP

Array is a data type used to describe a collection of elements. An array can be one-dimensional or multidimensional array. In VBScript, array can be represented as follows:


Dim arrayOned(6) - represent a dimension array which can store 7 elements. Index starts from 0.
Dim arraytwod(6)(4) - represents a two dimensional array which can store 7*5 =35 element
Dim(6)(4)(5) - Represents a three dimensional array. We can describe  n-dimension array in similar ways.

The above arrays are example of fixed array. Once we specify an array with dim and providing size of array, it is created as fixed dimension array. We cannot change the size of the array.
We can also create dynamic array in VBScript as shown below:

dim arraydynam() - create a variable without providing the size of array.Redim arraydynam(10) - we can then assign a size to the array by using redim. We can resize the array size as when required. 


On reducing the size of the array, loss of information can take place, so care should be taken while reducing the size of array in dynamic array.


There are some useful inbuilt functions in VBScript used to work with arrays. Let us discuss on the same.


Split Function - Split can be used to split a string into array based on the delimiter provided. Syntax for Split function is:

Split (expression [, delimiter [, count [, compare]]]) - here expression denotes the string which will be splitted based on the delimiter provided. 
Count and compare are optional with default value as -1 (repeats all substring) and binary compare. Default delimiter used is space.

Ubound function - Ubound returns largest subscript for the provided dimension of an array. In Case of argument for dimension not provided, it gives the ubound for first dimension

UBound(array, dimension))

Lbound function - Lbound returns smallest subscript for the provided dimension of an array. In Case of argument for dimension not provided, it gives the lbound for first dimension

UBound(array, dimension))

Join Function - Join function does opposite of what Split function does. It joins all the elements in the array using the delimiter. Syntax of function is:Join(array, delimiter)

In case of join also, the default delimiter if not provided is space character.

Filter Function - Filter is used to create a sub array from array matching the particular condition.
Filter(array, value, include, compare) - In the function, include and compare are optional parameters, include can have value true or false, true for searching for element with particular value matching and false to return elements which do not have match the condition

Array function - This function creates an array based on array element provided in the argument.

e.g. : a = array ("testing ", "array", "by" ,"creating", "array", "using array functions)

IsArray function returns true/false that indicates whether a specified variable is an array or not


''A simple code explaining the various functions for array manipulation

dim arr, strjoin
arr = split("this,is, wonderfrul, test",",") ' create an array using split function
ilowbound = lbound(arr) 'get lowerbound and upperbound for array
iupperbnd = ubound(arr)
for i=ilowboud to iupperbnd Step 1 '' Loop the array element
msgbox arr(i)
Next
b= filter(arr, "t")
msgbox b(1)
strjoin = join(arr, ";")
msgbox strjoin
msgbox Isarray(arr)

Understanding operators and built-in String functions in VBScript

In the previous article we discuss on defining a variable, different types of variables in VBscript . In this article we will discuss on various operators and built in string functions in VBScript as are frequently used in QTP.

Let us start by discussing different types of operators. Operators are broadly classified into 
- Logical Operators
- Arithmetic operators
- Comparison Operators

Logical Operators - Logical Operator are used to perform logical operations and returns boolean value as true or false based on the inputs provided and operator used.

Logical Operator used are Not ( Not True = false)
And (Returns true if both A and B are true, false otherwise)
OR(Returns true if either of A or B is true)
xor ( returns false if either of A or B is true)

Arithmetic Operators - We have been performing arithmetic operation from the day we start our education. So this is easy.  The various arithmetic operators in VBScript  are +(addition), - (subtraction), *(multiply), /(division), 
\(integer division, return the quotient), 
mod (a mod b, gives the remainder on dividing a by b),
^(exponential function).
Of the Operators , defined above , + is used to concatenate two strings also.

Comparison Operators are used to compare two variable . Example of comparison Operators are =(equality), <>(Inequality), <(Less than ), <(greater than), <=,>= ( greater than or equal to). To Compare strings, we can use strcomp function.

We have discussed the various operators used in VBScript.Now let us discuss on various string functions that are inbuilt in vbscript and are useful to work with strings

Instr function - This function returns the location of first occurrence of one string within another string. 
str1 = "This is testing blog on VBScript testing"
str2 = "testing"
iLoc = Instr(1,str1,str2,0)
msgbox iLoc

Syntax is InStr([start,]string1,string2[,compare]). start and compare are optional parameters with default value as 1 and 0(binary compare)

Instrrev function - This function returns the location of first occurrence of one string within another string. While Instr starts search from start of string,In Instrrev The search begins from the end of string. But the location returned is from start of string.
str1 = "This is testing blog on VBSCRIPT testing test"
str2 = "testing"
iLoc = Instrrev(str1,str2,-1,0)
msgbox iLoc

Syntax is InStrRev(string1,string2,[start,][compare]). start and compare are optional parameters with default value as -1(end of string) and 0(binary compare)

LCase(string) converts string to lowercase
Ucase(string) converts to uppercase.

len(string) returns number of character in a string.

Left, right and mid are used to return specified characters from the string starting from left,right, and middle of string
str3 = left(str1,10)
str4= right(str1, 10)
str5 = mid(str1,5,10) 

LTrim,RTrim and trim are used to remove spaces on the left, right or middle of a string
str6 = trim(str1)

strComp compares two string and returns value as 0 if both string matches.
blncomp = strcomp(str1,str2[,compare])

space(number) returns the space character returned times as provided in the argument.

String(number, character) returns a string with character repeated number of times as provided in the arguments.

VB Script tutorial - Variables, Constants and Arrays

VBScript is used extensively with QTP for creating test script. With articles on VBScript, I will try to explain the VBscript and refresh the concepts for my self knowledge.
In VBscript, variables of all the data types are declared with the same data type called as variant


A variable can be defined as Dim abc. We may or may not need to define the variable explicitly. If we require every variable used must be defined. we need to provide option explicit.
Using Option explicit is a good practice as it keeps a check on the variables used in the script

Some Important point to note about variable declaration are :

  • Variable for all the data type are defined as dim in vbscript
  • VBScript is not case sensitive, therefore variable abc and ABC are the same.
  • If Option explicit statement is defined, each of the variables used in the vbs file must be declared before use.
  • A variable must start with alphabet and should not exceed 255 characters
  • We can define variable everywhere in the script but it is best to define all the variable at the start of the function or script for better maintenance of variables
  • We can ignore standard naming convention by defining the variable within square bracket but should avoid this.
  • Multiple variable can be defined as Dim abc,def,qrtin 
We can also define an array variable, to store a set of values in a variable. An array can be one dimensional or multidimensional;'' For e.g. in below example we define the fixed size array, on trying on resize the array, it gives us error.
dim arra(5)
An array can be defined as dynamic array, we can resize the array then, below code explains how to create a dynamic array. Preserve is used to preserve value 
dim arrad() '' define a dynamic array variable without size provided
An variable defined at a function level can be used within the function in which it is defined. A variable defined at script level, can be used across the functions within the script. 
const abcd = 3

Option explicit
dim abc
abc = 3
msgbox abc



Dim [1Test 231]
[1Test 231] = "I have defined a variable not starting with alphabet and having a space in between"
msgbox [1Test 231]

An array can be a fixed size array defined as dim arra(5) , this will store 6 elements, but once defined the array size can not be modified. 


redim arra(3) 
arra(0) = 54 
msgbox arra(0)


redim arrad(3) '' Using Redim, we can define the size of the array. 
arrad(3) = 75  
redim preserve arrad(5) '' we use preserve the values stored on existing array using preserve as shown here. In this example we resized the array size to 5 and preserved the original value stored in array.
msgbox arrad(3)
We can also create multiple dimension array as dim arram(4)(5)(6).

In QTP, we can also define environment variable to be used across the actions.


Another type of variable in constant. A constant variable does not change its value once defined. Also value cannot to assigned to a constant post declaration of constant and its value

abcd = 43
msgbox abcd

QTP VBScript - Excel Application - Sorting data in excel worksheet based on column name

Below script or code snippet is very useful in sorting an excel workbook based on the name of columns header . We can sort multiple columns of the excel worksheet. For e.g there are 3 columns with header name as "name","class" and "value" based on which we want to sort the database with priority in order name>class>value. So provide strSortbyfield as "name>class>value". Below piecee of code can be implemented to achieve the same


strWorkBook = InputBox ("Input the workbook with full path")

strWorkSheet = InputBox("Enter the sheet name")

strSortbyFields = Inputbox ("provide the field names, seperated by > in case of multiple sorting of data is required")

Set objExcel = Createobject("Excel.Application")

objExcel.Visible = False

Set XLWorkBook = objExcel.WorkBooks.Open(strWorkbook)

Set objWorksheet = XLWorkBook.Worksheets(strWorkSheet)  

Set objRange = objWorksheet.UsedRange

ColCount = objRange.columns.count

strSortDataArr = split(strSortbyFields,">")

intCnt = ubound(strSortDataArr)

For i = intCnt to 0 step -1

For j = 1 to ColCount step 1

If (objWorkSheet.cells(1,j).value =strSortDataArr(i)) Then

''get the column based on which data needs to be sorted in the excel document

chrCde = Chr(asc("A")- 1+j) & "1"

boolExcelSortData = True

Set objRangeSrt = objExcel.Range(chrCde)

objRange.Sort objRangeSrt, xlDescending, , , , , , xlYes 

XLWorkBook.save

             Exit For

End If  

Next

Next

''save the workbook and close

XLWorkBook.Save

XLWorkBook.Close

objExcel.Quit

Set XLwORKBook = Nothing

Set objExcel = Nothing



How to write to Text Files using fileSystemObject in QTP

Using FileSystemObject we can write data to a text file. Below are the steps to write to a text file.


1. Create an instance of the FileSystemObject

 This is done through
Set objFSO = CreateObject("Scripting.FileSystemObject")

2. Use OpenTextFile to open an existing file or CreateTextFile to create a new text file to write data into.

Set otf = objFSO.CreateTextFile(FilePath,[OverWrite])
where FilePath is path of file to be created.OverWrite – Flag for overwriting content 

OR

 Set otf = objFSO.OpenTextFile(FilePath,ioMode)

where FilePath is path of file to be opened.ioMode – Define mode in which file to be opened. Use 1 to overwrite data and 8 to append data. 


3. Use below methods to write to the file.


a. Write(strText) - Write specified string in the text file.

Otf.Write(strText)

b. Writeline(strText) - writes a specified string and newline character.

otf.writeline(strText)

c. WriteblankLines(intLine) - Writes the specified number of blank lines in the text file

otf.WriteblankLines(4)

4. Close the text file.

otf.close This will close the file. It will close the text file. Note file is saved automatically when we write to a text file.


5. Set all objects as nothing


How to read text files in QTP using VBScript- Working With FileSystem Object


We can read the content of a text file using FileSystemObject methods and properties. Below are the various methods and properties used to extract data from file.

1. Creating an instance of filesystem object

Before reading content from a file, we have to create instance of filesystemobject.
Set objFSO = CreateObject("Scripting.FileSystemObject")

2. Opening an existing file to read

Set objTxtFile = objFSO.OpenTextFile(FilePath,iomode)

Iomode can have following values:

0 – For reading – opens the file for reading.
1 – For Writing – opens the file for writing, does overwrite the existing content in file.
8 – For Appending – opens the file for appending, new content is appended at the end of file.

3. ReadAll method 

It stores all the content of a file in a variable as string.sContent = objTxtFile.ReadAll

4. ReadLine method

It allows a script to read individual lines in a text file.
sContent = objTxtFile.Readline.
To read through all lines, use a Do Loop that continues until the AtEndOfStream property is True.
Below code snippet shows how to read through each line.

i=0
Do Until objTxtFile.AtEndOfStream
        sContent = objTxtFile.ReadLine
        sDataArray(i) = objTxtFile.ReadLine
        MsgBox sContent
        i = i+1
Loop

Content of each line can be stored in an array also.

5. Read(chr) 

 The Read method allows you to read only a specified number of characters.
Stores number of characters as defined in chr.

sContent = objTxtFile.Read(5)

6. Skip(chr) 

This method skips the number of characters defined in chr from the text file
skip(5)

7. SkipLine

This method skips line of data from the text file.
skipline

8. AtEndOfLine Property

 Returns true if the file pointer is positioned immediately before the end-of-line marker in a TextStream file. Can be useful to find characters in a line or reading characters till end of line.
Do While file.AtEndOfLine <> True 

9. Line property

gives the current line number of the textStream.
objTxtFile.line

10. Column Property

 Read-only property that returns the column number of the current character position in a TextStream file.
objTxtFile.Column       

11. OpenasTextStream Method

This method is used with getfile method to read from file.

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTxtFile = objFSO.getFile(FilePath)
var objts = objTxtFile.OpenAsTextStream(iomode)

FileSystemObject - Manipulation of Files and Files Properties

This post shows what are the basic operation we can do on files using filesystemobject in VBScript. We will discuss on writing to a file and reading from file in next posts.

Below are the tasks we can perform on files using filesystemobject and the properties of file object through which we can extract useful information. 


Tasks Performed on files are as follows: 

1. Creating object for FSO.

2. Verify if file exists.

3. binding to existing file

4. Creating a new text file.

5. Copy or moving a file

6. Deleting a file



Tasks performed on Files
Tasks performed on Files

Properties of File Object
Properties of File Object

How to Work with Folders in QTP using filesystemObject

Below are the tasks which we can perform with folders and properties of folder object which can be used to manipulate folders.

  • Creating object for FSO
  • Verifying existing of an Object
  • Binding to an existing folder
  • Creating a new folder
  • Deleting a folder
  • Copying or moving folder.

Tasks for folder using filesystemobject
Tasks for folder using filesystemobject


Properties of Folder Object
Properties of Folder Object