VBScript for QTP




VBScript (Visual Basic Scripting)


It is an Active Scripting language developed by Microsoft that is modeled on Visual Basic. It is designed as a “lightweight” language with a fast interpreter for use in a wide variety of Microsoft environments.

VBScript uses the Component Object Model to access elements of the environment within which it is running; for example, the FileSystemObject (FSO) is used to create, read, update and delete files.

VBScript has been installed by default in every desktop release of Microsoft Windows since Windows 98.

VBScript is the scripting language used in Quick Test Professional tool to enhance the automation.



Descriptive Programming
Descriptive programming is used in many scenarios like -> When QTP is not able to identify objects from properties value stored in Object Repository. -> When user do not want to use object repository or bypass it. -> When user wants to write a piece of code that can run on more than one website.

It is used in two ways:
1. Static Descriptive programming - Here we use properties and values directly in test script to access an object. For example: Browser("micClass:=.....").Page("micClass:=...").Link("micClass:=...")
2. Dynamic Descriptive programming - Here we create a description object and then operate on that. For example:
Set objTest = Description.Create
objTest("micClass").Value = "Link"
objTest("name").value = "Click Here"


Sorting array data

arrData = Array(324,234,33,7,467,34) '--->Or arrData = Array("Kite","Apple","Zebra","Banana")

For i = LBound(arrData) to UBound(arrData)
  For j = LBound(arrData) to UBound(arrData)
    If j <> UBound(arrData) Then
      If arrData(j) > arrData(j + 1) Then
         TempValue = arrData(j + 1)
         arrData(j + 1) = arrData(j)
         arrData(j) = TempValue
      End If
    End If
  Next
Next

For Each arrVal in arrData
   srtOrder = srtOrder & ", " & arrVal
   msgbox  srtOrder
Next



Reverse string without using strReverse() 

MyStr = inputbox("Enter the String:")
nCnt = Len(MyStr)
For i = 1 to nCnt
   RevStr = Mid(MyStr,i,1)&RevStr
Next
Msgbox RevStr 



Count string characters without using LEN() 

dim x
x = "hello"

'Method1:
'x = x&"@"
'msgbox Instr(1, x, "@")+1

'Method2:
res= instrrev(x,"")
msgbox res 


Count char occurrence 

strData = "an aeroplane in high sky"

'Method 1:
'cnt = 0
'srchChar = "a"
'for i = 1 to len(strData)
  'actAlpha = mid(strData,i,1)
   'if strComp(srchChar,actAlpha) = 0 then
  '    cnt = cnt + 1
 '  end if
'next
'msgbox cnt

'Method 2:
resCnt = Len(strData) - Len(Replace(strData, "a", ""))
msgbox resCnt


Access data from Excel (as DB connection)


strFileName = "<.xls data file path>"
 

Set con = CreateObject("adodb.connection")
Set rs = CreateObject("adodb.recordset")

con.Open "DRIVER={Microsoft Excel Driver (*.xls)};DBQ="&strFileName & ";Readonly=True"

msgbox con.State  '--To check the DB connection state

rs.Open "Select * from [Sheet1$]",con

msgbox rs.Fields(0).Value
msgbox rs.Fields(1).Value



Working with WebTable

'***************************************************
'Retrieve cell data from WebTable

'Method used - GetCellData(Row#,Col#)

'1.) For single cell data
'strCellData = Browser("").Page("").WebTable("").GetCellData(1, 1)
'msgbox strCellData

'2.) For whole webtable
cntRow = Browser("").Page("").WebTable("").RowCount
cntCol = Browser("").Page("").WebTable("").ColumnCount(cntRow)

For i=1 to cntRow
    For j = 1 to cntCol
            strCellData = Browser("").Page("").WebTable("").GetCellData(i,j)
            msgbox strCellData
      Next
Next



 

'Accessing childobjects from WebTable

Set objWebEdit = Description.Create
objWebEdit("micclass").value = "WebEdit"
set objColl = Browser("").Page("").WebTable("").ChildObjects(objWebEdit)
objCollCnt = objColl.count

For i = 0 to objCollCnt-1
    msgbox objColl(i).GetROProperty("html id")
Next


'Accessing childobjects from WebTable cells

'Method used - ChildItem(Row#,Col#,"<WebObjectClassName>",Index#)

cntRow = Browser("").Page("").WebTable("").RowCount
cntCol = Browser("").Page("").WebTable("").ColumnCount(cntRow)

For i=1 to cntRow
    For j = 1 to cntCol
            objCount = Browser("").Page("").WebTable("").ChildItemCount(i,j,"WebEdit") '---> To get the object count
            msgbox objCount
            For k = 0 to objCount-1
                set cellObj = Browser("").Page("").WebTable("").ChildItem(i,j,"WebEdit",k)
                msgbox cellObj.GetROProperty("html id")
            Next
      Next
Next
'***************************************************


Extract numeric data from string


'To extract numeric values from alphanumeric string:
Dim strData, strLen
strData = "testing123ofqtpwith789numbers"
strLen = Len(strData)
For i = 1 To strLen
    If Asc(Mid(strData, i, 1)) <> 32 Then
        If Asc(Mid(strData, i, 1)) >= 48 And Asc(Mid(strData, i, 1)) <= 57 Then
            intNum = intNum & Mid(strData, i, 1)
        End If
    Else
        msgbox("No numeric value available.")
    End If
Next
msgbox intNum 



To verify the string is Palindrome


str = "Malayalam" '--> Palindrome Sample
'str = "Hello"  '--> Not a Palindrome Sample
revStr=""
For i = 1 to len(str)
    revStr = mid(str,i,1) & revStr
Next
If strComp(str,revStr)=0 Then
    msgbox "The input string: " & str & " is a Palindrome."
Else
    msgbox "The input string: " & str & " is NOT a Palindrome."
End If


Sending e-mail with CDO

'CDO (Collaboration Data Objects) is a Microsoft technology that is designed to simplify the creation of messaging applications.

Set objEmailMessage = CreateObject("CDO.Message")

objEmailMessage.From = "abc@xyz.com"

objEmailMessage.To = "abc@xyz.com"

objEmailMessage.Cc = "111@aaa.com; 222@bbb.com; 333@ccc.com"

objEmailMessage.BCc = "zzz@abc.com"

objEmailMessage.Subject = "Test Report Email"

sMessage = sMessage & "All TC Executed  " & "Total:"& Count & "   " & "Pass:" & TestPassCount & "   " & "Fail:" & TestFailCount & "<BR>" & VBCR
sMessage = sMessage & "<P>" & VBCR
sMessage = sMessage & "<table style='border:1px solid black;border-collapse:collapse;'><tr><th style='border:1px solid black;'>S.no</th><th style='border:1px solid black;'> Test Case Name</th><th style='border:1px solid black;'>Status</th><th style='border:1px solid black;'>Comments</th></tr>"& VBCR
sMessage = sMessage & "<p>" & VBCR
sMessage = sMessage & "Regards,<br>" & vbLf
sMessage = sMessage & "Automation Team<br>" & VBCR

objEmailMessage.HTMLBody = sMessage

objEmailMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
objEmailMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objEmailMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objEmailMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
objEmailMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
objEmailMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 20
objEmailMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "test@gmail.com"
objEmailMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "*********"

objEmailMessage.AddAttachment("FilePath")

objEmailMessage.Configuration.Fields.Update

objEmailMessage.Send     
        
Set objEmailMessage = nothing

'Reference: http://www.w3schools.com/asp/asp_send_email.asp

                http://www.paulsadowski.com/wsh/cdo.htm


Closing all tabs except current one in IE


strRequiredTab="Expected browser name to be closed"

Set obj=description.Create
obj("micclass").value="Browser"

Set childObjs=Desktop.ChildObjects(obj)
childCount=childObjs.count
For i=0 to childCount-1
    strBrowserName=childObjs(i).getROProperty("name")
    If strBrowserName <> strRequiredTab Then
        strVal="hwnd:="&childObjs(i).getROProperty("hwnd")
        browser(strVal).close
    End If
Next 



List hyperlinks from an excel sheet and click them


Dim linkCount, objExcel, objworkbook, objSheet, rowcount

linkCount = 0

Set objExcel = CreateObject("Excel.Application")
Set objworkbook = objExcel.Workbooks.Open("D:\LinkTest.xls")
Set objSheet = objExcel.Worksheets(1)

rowcount = objSheet.UsedRange.Rows.count

For i = 1 to rowcount
    For j = 1 To 1  '==> going for how many column in excel file.
        If  objExcel.Cells(i, j).HyperLinks.Count > 0 Then
            strCellValue = objExcel.Cells(i, j).Hyperlinks(1).TextToDisplay ' ==> The cell value
            strHyperLinkValue = objExcel.Cells(i, j).Hyperlinks(1).Address '==> The url which is mapped to the cell
            MsgBox "Cell value : " & strCellValue  & Chr(13) & "Hyperlink : " &  strHyperLinkValue
            objExcel.Cells(i, j).Hyperlinks(1).Follow '==> This will enable to click the link of the cell.
            wait 10
            linkCount = linkCount + 1 '==> To count the number of links available is a sheet
        End If      
    Next
Next

objExcel.Workbooks.Close
set objSheet = Nothing
Set objworkbook = Nothing
Set objExcel = Nothing
objExcel.quit  



Reverse each word and convert initial char of word from lower to upper

'Example:
'Input string = "hello how are you"
'Expected Output = "Olleh Woh Era Uoy"

strVal = "hello how are you"
strArr = split(strVal, " ")
For  i = 0 to UBound(strArr)
    revStr = StrReverse(strArr(i))
    repStr = Replace(revStr, left(revStr, 1), ucase(left(revStr, 1)))
    reverseInitCapStr = reverseInitCapStr & " " & repStr
Next

MsgBox reverseInitCapStr

How to fetch tooltip text of an object


Browser("B").Page("P").Image("I").FireEvent "onmouseover"
wait 1
strToolTip = Window("nativeclass:=tooltips_class32").GetROProperty("text")
msgbox strToolTip

How to sort Excel data

Const xlAscending = 1 'represents the sorting type 1 for Ascending 2 for Desc
Const xlYes = 1

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Open("<path>.xls")

Set objWorksheet = objWorkbook.Worksheets(1)
Set objRange = objWorksheet.UsedRange
Set objRange2 = objExcel.Range("C1") 'which column to be used to sort entire sheet.

objRange.Sort objRange2, xlAscending, , , , , , xlYes
set objExcel=nothing

No comments:

Post a Comment