• Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
3,904
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
638
Comments
0
Likes
4

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. For QTP RealTime scripts visit: www.ramupalanki.com VBScript Tutorial (For QTP) 1) Introduction 2) Comments 3) VB Script Variables 4) VB Script Data Types 5) VB Script Operators 6) Input/Output Operations 7) Constants 8) Conditional Statements 9) General Examples 10)Loop Through Code 11)Procedures 12)Built-In Functions 13)VBScript syntax rules and guidelines 14)Errors 15)File System Operations 16)Test Requirements 17) Solutions 18)QTP Add-Ins Information 19) VBScript Glossarywww.ramupalanki.com
  • 2. For QTP RealTime scripts visit: www.ramupalanki.com Introduction o VBScript is a scripting language. o A scripting language is a lightweight programming language. o VBScript is a light version of Microsofts programming language Visual Basic.When a VBScript is inserted into a HTML document, the Internet browser will readthe HTML and interpret the VBScript. The VBScript can be executed immediately, orat a later event.Microsoft Visual Basic Scripting Edition brings active scripting to a wide variety ofenvironments, including Web client scripting in Microsoft Internet Explorer and Webserver scripting in Microsoft Internet Information Service.1.1 Windows Script Host (WSH)It is a Windows administration tool. WSH creates an environment for hosting scripts.That is, when a script arrives at your computer, WSH plays the part of the host — itmakes objects and services available for the script and provides a set of guidelineswithin which the script is executed. Among other things, Windows Script Hostmanages security and invokes the appropriate script engineWindows Script Host is built into Microsoft Windows 98, 2000, and MillenniumEditions and higher versions.A Windows script is a text file. We can create a script with any text editor as long aswe save our script with a WSH-compatible script extension (.js, vbs, or .wsf).The most commonly available text editor is already installed on our computer —Notepad. We can also use your favorite HTML editor, VbsEdit, Microsoft Visual C++,or Visual InterDev.1.2 Creating a script with Notepad1.Start Notepad.2.Write your script. For example purposes, type Msgbox "Hello VB Script"3.Save this text file with a .vbs extension (instead of the default .txt extension). Forexample, Hello.vbs4.Navigate to the file you just saved, and double-click it.5.Windows Script Host invokes the VB Script engine and runs your script. In theexample, a message box is displayed with the message "Hello VB Script"1.3 Hosting Environments and Script EnginesScripts are often embedded in Web pages, either in an HTML page (on the clientside) or in an ASP page (on the server side).www.ramupalanki.com
  • 3. For QTP RealTime scripts visit: www.ramupalanki.comIn the case of a script embedded in an HTML page, the engine component thatinterprets and runs the script code is loaded by the Web browser, such as InternetExplorer.In the case of a script embedded in an ASP page, the engine that interprets and runsthe script code is built into Internet Information Services (IIS).Windows Script Host executes scripts that exist outside an HTML or ASP page andthat stand on their own as text files.1.4 Available Script EnginesGenerally, we write scripts in either Microsoft JScript or VBScript, the two scriptengines that ship with Microsoft Windows 98, 2000 and Millennium Editions.We can use other script engines, such as Perl, REXX, and Python, with WindowsScript Host.A stand-alone script written in JScript has the .js extension; a stand-alone scriptwritten in VBScript has the .vbs extension. These extensions are registered withWindows. When we run one of these types of files, Windows starts Windows ScriptHost, which invokes the associated script engine to interpret and run the file.www.ramupalanki.com
  • 4. For QTP RealTime scripts visit: www.ramupalanki.com CommentsThe comment argument is the text of any comment we want to include.2.0 Purpose of comments: o We can use comments for making the script understandable. o We can use comments for making one or more statements disable from execution.2.1 SyntaxRem comment (After the Rem keyword, a space is required before comment.) OrApostrophe () symbol before the comment2.2 Comment/Uncomment a block of statementsSelect block of statement and use short cut key Ctrl + M (for comment)Select comment block and use short cut key Ctrl + Shift + M (for uncomment)2.3 Examplewww.ramupalanki.com
  • 5. For QTP RealTime scripts visit: www.ramupalanki.com VB Script VariablesA variable is a convenient placeholder that refers to a computer memory locationwhere we can store program information that may change during the time our scriptis running.3.1 Declaring VariablesWe declare variables explicitly in our script using the Dim statement, the Publicstatement, and the Private statement.For example:Dim cityDim xWe declare multiple variables by separating each variable name with a comma. ForExample:Dim x, Top, Bottom, Left, RightWe can also declare a variable implicitly by simply using its name in our script. Thatis not generally a good practice because we could misspell the variable name in oneor more places, causing unexpected results when our script is run. For that reason,the Option Explicit statement is available to require explicit declaration of allvariables.The Option Explicit statement should be the first statement in our script.3.2 Option ExplicitForces explicit declaration of all variables in a script.Option Explicit Force explicit variable declaration.Dim MyVar Declare variable.MyInt = 10 Undeclared variable generates error.MyVar = 10 Declared variable does not generate error.3.3 Naming Restrictions for VariablesVariable names follow the standard rules for naming anything in VBScript. A variablename: o Must begin with an alphabetic character. o Cannot contain an embedded period. o Must not exceed 255 characters. o Must be unique in the scope in which it is declared.www.ramupalanki.com
  • 6. For QTP RealTime scripts visit: www.ramupalanki.com3.4 Scope of VariablesA variables scope is determined by where we declare it.When we declare a variable within a procedure, only code within that procedure canaccess or change the value of that variable.If we declare a variable outside a procedure, we make it recognizable to all theprocedures in our script. This is a script-level variable, and it has script-level scope.3.5 Life Time of VariablesThe lifetime of a variable depends on how long it exists.The lifetime of a script-level variable extends from the time it is declared until thetime the script is finished running.At procedure level, a variable exists only as long as you are in the procedure.3.6 Assigning Values to VariablesValues are assigned to variables creating an expression as follows:The variable is on the left side of the expression and the value you want to assign tothe variable is on the right.For example:A = 200City = “Hyderabad”X=100: Y=2003.7 Scalar Variables and Array VariablesA variable containing a single value is a scalar variable.A variable containing a series of values, is called an array variable.Array variables and scalar variables are declared in the same way, except that thedeclaration of an array variable uses parentheses () following the variable name.Example:Dim A(3)Although the number shown in the parentheses is 3, all arrays in VBScript are zero-based, so this array actually contains 4 elements.We assign data to each of the elements of the array using an index into the array.Beginning at zero and ending at 4, data can be assigned to the elements of an arrayas follows:www.ramupalanki.com
  • 7. For QTP RealTime scripts visit: www.ramupalanki.comA(0) = 256A(1) = 324A(2) = 100A(3) = 55Similarly, the data can be retrieved from any element using an index into theparticular array element you want.For example:SomeVariable = A(4)Arrays arent limited to a single dimension. We can have as many as 60 dimensions,although most people cant comprehend more than three or four dimensions.In the following example, the MyTable variable is a two-dimensional array consistingof 6 rows and 11 columns:Dim MyTable(5, 10)In a two-dimensional array, the first number is always the number of rows; thesecond number is the number of columns.3.8 Dynamic ArraysWe can also declare an array whose size changes during the time our script isrunning. This is called a dynamic array.The array is initially declared within a procedure using either the Dim statement orusing the ReDim statement.However, for a dynamic array, no size or number of dimensions is placed inside theparentheses.For example:Dim MyArray()ReDim AnotherArray()To use a dynamic array, you must subsequently use ReDim to determine the numberof dimensions and the size of each dimension.In the following example, ReDim sets the initial size of the dynamic array to 25. Asubsequent ReDim statement resizes the array to 30, but uses the Preserve keywordto preserve the contents of the array as the resizing takes place.ReDim MyArray(25)ReDim Preserve MyArray(30)There is no limit to the number of times we can resize a dynamic array, although ifwe make an array smaller, we lose the data in the eliminated elements.www.ramupalanki.com
  • 8. For QTP RealTime scripts visit: www.ramupalanki.com VB Script Data TypesVBScript has only one data type called a Variant. A Variant is a special kind of datatype that can contain different kinds of information, depending on how it is used.Because Variant is the only data type in VBScript, it is also the data type returned byall functions in VBScript.4.1 Variant SubtypesBeyond the simple numeric or string classifications, a Variant can make furtherdistinctions about the specific nature of numeric information. For example, we canhave numeric information that represents a date or a time. When used with otherdate or time data, the result is always expressed as a date or a time. We can alsohave a rich variety of numeric information ranging in size from Boolean values tohuge floating-point numbers. These different categories of information that can becontained in a Variant are called subtypes. Most of the time, we can just put the kindof data we want in a Variant, and the Variant behaves in a way that is mostappropriate for the data it contains.The following table shows subtypes of data that a Variant can contain.Subtype DescriptionEmpty Variant is uninitialized. Value is 0 for numeric variables or a zero-length string("") for string variables.Null Variant intentionally contains no valid data.Boolean Contains either True or False.Byte Contains integer in the range 0 to 255.Integer Contains integer in the range -32,768 to 32,767.Currency -922,337,203,685,477.5808 to 922,337,203,685,477.5807.Long Contains integer in the range -2,147,483,648 to 2,147,483,647.Single Contains a single-precision, floating-point number in the range -3.402823E38to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positivevalues.Double Contains a double-precision, floating-point number in the range-1.79769313486232E308 to -4.94065645841247E-324 for negative values;4.94065645841247E-324 to 1.79769313486232E308 for positive values.Date (Time) Contains a number that represents a date between January 1, 100 toDecember 31, 9999.String Contains a variable-length string that can be up to approximately 2 billioncharacters in length.Object Contains an object.Error Contains an error number.We can use conversion functions to convert data from one subtype to another. Inaddition, the VarType function returns information about how your data is storedwithin a Variant.www.ramupalanki.com
  • 9. For QTP RealTime scripts visit: www.ramupalanki.com VB Script OperatorsOperators are used for performing mathematical, comparison and logical operations.VBScript has a full range of operators, including arithmetic operators, comparisonoperators, concatenation operators, and logical operators.4.1 Operator PrecedenceWhen several operations occur in an expression, each part is evaluated and resolvedin a predetermined order called operator precedence.We can use parentheses to override the order of precedence and force some parts ofan expression to be evaluated before others.Operations within parentheses are always performed before those outside. Withinparentheses, however, standard operator precedence is maintained.When expressions contain operators from more than one category, arithmeticoperators are evaluated first, comparison operators are evaluated next, and logicaloperators are evaluated last.Comparison operators all have equal precedence; that is, they are evaluated in theleft-to-right order in which they appear.Arithmetic and logical operators are evaluated in the following order of precedence.4.2 Arithmetic Operators:Operator Description1) Exponentiation Operator (^) Raises a number to the power of an exponent2) Multiplication Operator (*) Multiplies two numbers.3) Division Operator (/) Divides two numbers and returns a floating-point result.4) Integer Division Operator () Divides two numbers and returns an integer result.5) Mod Operator Divides two numbers and returns only the remainder.6) Addition Operator (+) Sums two numbers.7) Subtraction Operator (-) Finds the difference between two numbers or indicates the negative value of a numeric expression.8) Concatenation Operator (&) Forces string concatenation of two expressions.4.3 Comparison OperatorsUsed to compare expressions.Operator Description1) = (Equal to) Used to compare expressions.2) <> (Not equal to) Used to compare expressions.3) < Less than4) > Grater than5) <= Less than or equal towww.ramupalanki.com
  • 10. For QTP RealTime scripts visit: www.ramupalanki.com6) >= Greater than or equal to7) Is Object equivalence4.4 Concatenation OperatorsOperator Description1) Addition Operator (+) Sums two numbers If Then 1) Both expressions are numeric Add. 2) Both expressions are strings Concatenate. 3) One expression is numeric and the other is a string Add.2) Concatenation Forces string concatenation of two expressions.Operator (&)4.5 Logical OperatorsOperator Description Syntax1) Not Performs logical negation on an result= Not expression expression2) And Performs a logical conjunction on two result= expression1 And expressions. expression23) Or Performs a logical disjunction on two result= expression1 Or expressions. expression24) Xor Performs a logical exclusion on two result= expression1 Xor expressions. expression25) Eqv Performs a logical equivalence on result= expression1 Eqv two expressions. expression26) Imp Performs a logical implication on two result= expression1 Imp expressions. expression2www.ramupalanki.com
  • 11. For QTP RealTime scripts visit: www.ramupalanki.com Input/Output Operations6.1 InputBox FunctionDisplays a prompt in a dialog box, waits for the user to input text or click a button,and returns the contents of the text box.Example:Dim InputInput = InputBox("Enter your name")MsgBox ("You entered: " & Input)6.2 MsgBox FunctionDisplays a message in a dialog box, waits for the user to click a button, and returns avalue indicating which button the user clicked.Example:Dim MyVarMyVar = MsgBox ("Hello World!", 65, "MsgBox Example") MyVar contains either 1 or 2, depending on which button is clicked.www.ramupalanki.com
  • 12. For QTP RealTime scripts visit: www.ramupalanki.com VB Script ConstantsA constant is a meaningful name that takes the place of a number or string andnever changes.7.1 Creating ConstantsWe create user-defined constants in VBScript using the Const statement. Using theConst statement, we can create string or numeric constants with meaningful namesand assign them literal values.Const statementDeclares constants for use in place of literal values.Example:Const MyString = "This is my string."Const MyAge = 49Const CutoffDate = #6-1-97#Note that String literal is enclosed in quotation marks (" ").Represent Date literals and time literals by enclosing them in number signs (#).We declare multiple constants by separating each constant name and value with acomma. For example:Const price= 100, city= “Hyderabad”, x= 27www.ramupalanki.com
  • 13. For QTP RealTime scripts visit: www.ramupalanki.com Conditional StatementsWe can control the flow of our script with conditional statements and loopingstatements.Using conditional statements, we can write VBScript code that makes decisions andrepeats actions. The following conditional statements are available in VBScript:1) If…Then…Else Statement2) Select Case Statement8.1 Making Decisions Using If...Then...ElseThe If...Then...Else statement is used to evaluate whether a condition is True orFalse and, depending on the result, to specify one or more statements to run.Usually the condition is an expression that uses a comparison operator to compareone value or variable with another.If...Then...Else statements can be nested to as many levels as you need.8.1.1 Running a Statement if a Condition is True (single statement)To run only one statement when a condition is True, use the single-line syntax forthe If...Then...Else statement.Dim myDate myDate = #2/13/98# If myDate < Now Then myDate = Now8.1.2 Running Statements if a Condition is True (multiple statements)To run more than one line of code, we must use the multiple-line (or block) syntax.This syntax includes the End If statement.Dim xx= 20If x>10 Then msgbox "Hello Tester"www.ramupalanki.com
  • 14. For QTP RealTime scripts visit: www.ramupalanki.com msgbox "x value is: "&x msgbox "Bye Bye"End If8.1.3 Running Certain Statements if a Condition is True and Running Othersif a Condition is FalseWe can use an If...Then...Else statement to define two blocks of executablestatements: one block to run if the condition is True, the other block to run if thecondition is False.Example:Dim xx= Inputbox (" Enter a value")If x>100 Then Msgbox "Hello Tester" Msgbox "X is a Big Number" Msgbox "X value is: "&XElse Msgbox "GCR" Msgbox "X is a Small Number" Msgbox "X value is: "&XEnd If8.1.4 Deciding Between Several AlternativesA variation on the If...Then...Else statement allows us to choose from severalalternatives. Adding ElseIf clauses expands the functionality of the If...Then...Elsestatement so we can control program flow based on different possibilities.Example:Dim xx= Inputbox (" Enter a value")If x>0 and x<=100 Then Msgbox "Hello Tester" Msgbox "X is a Small Number" Msgbox "X value is "&xElse IF x>100 and x<=500 Then Msgbox "Hello GCR" Msgbox "X is a Medium Number"Else IF x>500 and x<=1000 Then Msgbox "Hello Tester" Msgbox "X is a Large Number"Else Msgbox "Hello Sir" Msgbox "X is a Grand Number"End IfEnd IfEnd Ifwww.ramupalanki.com
  • 15. For QTP RealTime scripts visit: www.ramupalanki.com8.1.5 Executing a certain block of statements when two / more conditionsare True (Nested If...)Example:Dim State, RegionState=Inputbox ("Enter a State")Region=Inputbox ("Enter a Region")If state= "AP" Then If Region= "Telangana" Then msgbox "Hello Tester" msgbox "Dist count is 10"Else if Region= "Rayalasema" Then msgbox "Hello GCR" msgbox "Dist count is 4"Else If Region= "Costal" Then msgbox "Hello Tester" msgbox "Dist count is 9"End IfEnd IfEnd IfEnd If8.2 Making Decisions with Select CaseThe Select Case structure provides an alternative to If...Then...ElseIf for selectivelyexecuting one block of statements from among multiple blocks of statements. ASelect Case statement provides capability similar to the If...Then...Else statement,but it makes code more efficient and readable.Example:Option explicitDim x,y, Operation, Resultx= Inputbox (" Enter x value")y= Inputbox ("Enter y value")Operation= Inputbox ("Enter an Operation")Select Case Operation Case "add" Result= cdbl (x)+cdbl (y) Msgbox "Hello Tester" Msgbox "Addition of x,y values is "&Result Case "sub" Result= x-y Msgbox "Hello Tester"www.ramupalanki.com
  • 16. For QTP RealTime scripts visit: www.ramupalanki.com Msgbox "Substraction of x,y values is "&Result Case "mul" Result= x*y Msgbox "Hello Tester" Msgbox "Multiplication of x,y values is "&Result Case "div" Result= x/y Msgbox "Hello Tester" Msgbox "Division of x,y values is "&Result Case "mod" Result= x mod y Msgbox "Hello Tester" Msgbox "Mod of x,y values is "&Result Case "expo" Result= x^y Msgbox "Hello Tester" Msgbox"Exponentation of x,y values is "&Result Case Else Msgbox "Hello Tester" msgbox "Wrong Operation"End Select8.3 Other Examples8.3.1 Write a program for finding out whether the given year is a leap yearor not?Dim xyearxyear=inputbox ("Enter Year")If xyear mod 4=0 Then msgbox "This is a Leap year"Else msgbox "This is NOT"End If8.3.2 Write a program for finding out whether the given number is, Evennumber or Odd number?Dim numnum=inputbox ("Enter a number")If num mod 2=0 Then msgbox "This is a Even Number"Else msgbox "This is a Odd Number"www.ramupalanki.com
  • 17. For QTP RealTime scripts visit: www.ramupalanki.comEnd If8.3.3 Read two numbers and display the sum?Dim num1,num2, sumnum1=inputbox ("Enter num1")num2=inputbox ("Enter num2") sum= Cdbl (num1) + Cdbl (num2) if we want add two strings conversionrequire msgbox ("Sum is " &sum)8.3.4 Read P,T,R values and Calculate the Simple Interest?Dim p,t, r, sip=inputbox ("Enter Principle")t=inputbox ("Enter Time")r=inputbox ("Enter Rate of Interest") si= (p*t*r)/100 p= principle amount, t=time in years, r= rate of interest msgbox ("Simple Interest is " &si)8.3.5 Read Four digit number, calculate & display the sum of the number ordisplay Error message if the number is not a four digit number?Dim num, sumnum=inputbox ("Enter a Four digit number")If Len(num) = 4 Thensum=0 sum=sum+num mod 10 num=num/10 num= left (num, 3) sum=sum+num mod 10 num=num/10 num= left (num, 2) sum=sum+num mod 10 num=num/10 num= left (num, 1) sum=sum+num mod 10 msgbox ("Sum is " &sum)elsemsgbox "Number, you entered is not a 4 digit number"End If8.3.6 Read any Four-digit number and display the number in reverse order?Dim num,revnum= inputbox("Enter a number")If len(num)=4 Thenrev=rev*10 + num mod 10num=num/10num= left(num,3)www.ramupalanki.com
  • 18. For QTP RealTime scripts visit: www.ramupalanki.comrev=rev*10 + num mod 10num=num/10num= left(num,2)rev=rev*10 + num mod 10num=num/10num= left(num,1)rev=rev*10 + num mod 10 msgbox "Reverse Order of the number is "&revElse msgbox "Number, you entered is not a 4 digit number"End If8.3.7 Read 4 subjects marks; calculate the Total marks and grade?(a) If average marks Greater than or equal to 75, grade is Distinctionb) If average marks Greater than or equal to 60 and less than 75 , then grade isFirstc) If average marks Greater than or equal to 50 and less than 60 , then grade isSecondd) If average marks Greater than or equal to 40 and less than 50 , then grade isThirde) Minimum marks 35 for any subject, otherwise no grade fail)Dim e,m,p,c, tote=inputbox ("Enter english Marks")m=inputbox ("Enter maths Marks")p=inputbox ("Enter physics Marks")c=inputbox ("Enter chemistry Marks")tot= cdbl(e) + cdbl(m) + cdbl(p) + cdbl(c)msgbox totIf cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot>=300 Then msgbox "Grade is Distinction"else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot>=240 and tot<300 Then msgbox "Grade is First"else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot>=200 and tot<240 Then msgbox "Grade is Second"else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot>=160 and tot<200 Then msgbox "Grade is Third"elsewww.ramupalanki.com
  • 19. For QTP RealTime scripts visit: www.ramupalanki.commsgbox "No Grade, Fail"End IfEnd IfEnd IfEnd If8.3.8 Display Odd numbers up to n?Dim num,nn=Inputbox ("Enter a Vaule")For num= 1 to n step 2msgbox numNext8.3.9 Display Even numbers up to n?Dim num,nn=Inputbox ("Enter a Vaule")For num= 2 to n step 2msgbox numNext8.3.10 display natural numbers up to n and write in a text file?Dim num, n, fso, myfilen= inputbox ("Enter any Value")num=1For num= 1 to n step 1Set fso= createobject ("scripting.filesystemobject")set myfile=fso.opentextfile ("E:gcr.txt", 8, true)myfile.writeline nummyfile.closeNext8.11 Display Natural numbers in reverse order up to n?Dim num,nn=Inputbox ("Enter a Vaule")For num=n to 1 step -1msgbox numNext8.12 Display Natural numbers sum up to n? (Using For...Next Loop)Dim num, n, sumn= inputbox ("Enter a Value")sum=0For num= 1 to n step 1 sum= sum+numNext msgbox sumwww.ramupalanki.com
  • 20. For QTP RealTime scripts visit: www.ramupalanki.com8.13 Display Natural numbers sum up to n? (using While...Wend Loop)Dim num, n, sumn= inputbox ("Enter a Value")While num <=cdbl (n) sum= sum+num num=num+1Wend msgbox sum8.14 Display Natural numbers sum up to n? (Using Do...Until...Loop)Dim num, n, sumn= inputbox ("Enter a Value")sum=0num=1Do sum= sum+num num=num+1Loop Until num =cdbl (n+1) msgbox sum8.15 Write a Function for Natural Numbers sum up to n?Function NNumCou (n)Dim num, sumsum=0For num= 1 to n step 1 sum= sum+numNextmsgbox sumEnd Function8.16 Verify weather the entered 10 digit value is a numeric value or not?Dim a,x,y,z,numnum=Inputbox ("Enter a Phone Number")d1= left (num,1)d10=Right (num,1)d2=mid (num, 2, len (1))d3=mid (num, 3, len (1))d4=mid (num, 4, len (1))d5=mid (num, 5, len (1))d6=mid (num, 6, len (1))d7=mid (num, 7, len (1))d8=mid (num, 8, len (1))d9=mid (num, 9, len (1))www.ramupalanki.com
  • 21. For QTP RealTime scripts visit: www.ramupalanki.comIf isnumeric (d1) = "True" and isnumeric (d2) = "True" and isnumeric (d3) = "True"and isnumeric (d4) = "True"and isnumeric (d5) = "True"and isnumeric (d6) ="True"and isnumeric (d7) = "True"and isnumeric (d8) = "True"and isnumeric (d9) ="True"and isnumeric (d10) = "True" Then msgbox "It is a Numeric Value"else Msgbox "It is NOT Numeric" End If8.17 Verify weather the entered value is a 10 digit value or not and Numericvalue or not? (Using multiple if conditions)Dim a,x,y,z,numnum=Inputbox ("Enter a Phone Number")d1= left (num,1)d10=Right (num,1)d2=mid (num, 2, len (1))d3=mid (num, 3, len (1))d4=mid (num, 4, len (1))d5=mid (num, 5, len (1))d6=mid (num, 6, len (1))d7=mid (num, 7, len (1))d8=mid (num, 8, len (1))d9=mid (num, 9, len (1))If len (num) =10 ThenIf isnumeric (d1) = "True" and isnumeric (d2) = "True" and isnumeric (d3) = "True"and isnumeric (d4) = "True"and isnumeric (d5) = "True"and isnumeric (d6) ="True"and isnumeric (d7) = "True"and isnumeric (d8) = "True"and isnumeric (d9) ="True"and isnumeric (d10) = "True" Then msgbox "It is a Numeric Value"End IfEnd IfIf len (num) <> 10 Then Msgbox "It is NOT valid Number "End Ifwww.ramupalanki.com
  • 22. For QTP RealTime scripts visit: www.ramupalanki.com Looping Through Code o Looping allows us to run a group of statements repeatedly. o Some loops repeat statements until a condition is False; o Others repeat statements until a condition is True. o There are also loops that repeat statements a specific number of times.The following looping statements are available in VBScript: o Do...Loop: Loops while or until a condition is True. o While...Wend: Loops while a condition is True. o For...Next: Uses a counter to run statements a specified number of times. o For Each...Next: Repeats a group of statements for each item in a collection or each element of an array.9.1 Using Do LoopsWe can use Do...Loop statements to run a block of statements an indefinite numberof times.The statements are repeated either while a condition is True or until a conditionbecomes True.9.1.1 Repeating Statements While a Condition is TrueRepeats a block of statements while a condition is True or until a condition becomesTruea) Do While condition Statements ----------- ----------- LoopOr, we can use this below syntax:Example:Dim xwww.ramupalanki.com
  • 23. For QTP RealTime scripts visit: www.ramupalanki.comDo While x<5 x=x+1 Msgbox "Hello Tester" Msgbox "Hello QTP"Loopb) Do Statements ----------- ----------- Loop While conditionExample:Dim xx=1Do Msgbox "Hello Tester" Msgbox "Hello QTP" x=x+1Loop While x<59.1.2 Repeating a Statement Until a Condition Becomes Truec) Do Until condition Statements ----------- ----------- LoopOr, we can use this below syntax:Example:Dim xDo Until x=5 x=x+1 Msgbox "Tester" Msgbox "Hello QTP"LoopOr, we can use this below syntax:d) Do Statements ----------- ----------- Loop Until conditionOr, we can use this below syntax:Example:Dim xx=1DoMsgbox “Hello Tester”Msgbox "Hello QTP"www.ramupalanki.com
  • 24. For QTP RealTime scripts visit: www.ramupalanki.com x=x+1Loop Until x=59.2 While...Wend StatementExecutes a series of statements as long as a given condition is True.Syntax:While condition Statements ----------- -----------WendExample:Dim xx=0While x<5 x=x+1 msgbox "Hello Tester" msgbox "Hello QTP"Wend9.3 For...Next StatementRepeats a group of statements a specified number of times.Syntax:For counter = start to end [Step step] statementsNextExample:Dim xFor x= 1 to 5 step 1Msgbox "Hello Tester"Next9.4 For Each...Next StatementRepeats a group of statements for each element in an array or collection.Syntax:For Each item In array StatementsNextExample: (1Dim a,b,x (3)a=20b=30x(0)= "Addition is "& a+bx(1)="Substraction is " & a-bwww.ramupalanki.com
  • 25. For QTP RealTime scripts visit: www.ramupalanki.comx(2)= "Multiplication is " & a*bx(3)= "Division is " & a/bFor Each element In x msgbox elementNextExample: (2MyArray = Array("one","two","three","four","five")For Each element In MyArray msgbox elementNext Control Flow Examples (Using Conditional and Loop Statements)11.1 read a number and verify that number Range weather in between 1 to100 or 101 to 1000?Option explicitDim a,xa=Inputbox ("Enter a Vaule")a=cdbl(a)If a<= 100 ThenFor x= 1 to 100If a=x Then msgbox "a is in between 1 to 100 range"End IfNextelseFor x= 101 to 1000If a=x Thenmsgbox "a is in between 101 to 1000 range"End IfNextEnd If11.1 read Data and find that data size, If size <>4 then display invalid datamessage, if data size = 4 then verify “a” is there or not in that data?Dim xx=Inputbox ("Enter 4 digit value")x1=Right(x,1)x2=Left (x,1)x3=mid (x,2,Len(1))x4=mid (x,3,Len(1))y=len(x)If y=4 ThenIf x1="a" or x2="a" or x3="a" or x4="a" Thenmsgbox "a is there"elsemsgbox "a is Not there"www.ramupalanki.com
  • 26. For QTP RealTime scripts visit: www.ramupalanki.comEnd Ifelsemsgbox "Invalid Data"End If VB Script ProceduresIn VBScript, there are two kinds of procedures available; the Sub procedure and theFunction procedure.11.1 Sub ProceduresA Sub procedure is a series of VBScript statements (enclosed by Sub and End Substatements) that perform actions but dont return a value.A Sub procedure can take arguments (constants, variables, or expressions that arepassed by a calling procedure).If a Sub procedure has no arguments, its Sub statement must include an empty setof parentheses ().Syntax:Sub Procedure name ()Statements----------------------End SubOrSub Procedure name (argument1, argument2)Statements----------------------End SubExample: 1Sub ConvertTemp() temp = InputBox("Please enter the temperature in degrees F.", 1) MsgBox "The temperature is " & Celsius(temp) & " degrees C."End SubExample: 211.2 Function Procedureswww.ramupalanki.com
  • 27. For QTP RealTime scripts visit: www.ramupalanki.comA Function procedure is a series of VBScript statements enclosed by the Function andEnd Function statements.A Function procedure is similar to a Sub procedure, but can also return a value.A Function procedure can take arguments (constants, variables, or expressions thatare passed to it by a calling procedure).If a Function procedure has no arguments, its Function statement must include anempty set of parentheses.A Function returns a value by assigning a value to its name in one or morestatements of the procedure. The return type of a Function is always a Variant.Syntax:Function Procedure name ()Statements----------------------End FunctionOrFunction Procedure name (argument1, argument2)Statements----------------------End FunctionExample: 1Function Celsius(fDegrees) Celsius = (fDegrees - 32) * 5 / 9End FunctionExample: 2Function cal(a,b,c) cal = (a+b+c)End Function11.3 Getting Data into and out of Procedures o Each piece of data is passed into our procedures using an argument. o Arguments serve as placeholders for the data we want to pass into our procedure. We can name our arguments any valid variable name. o When we create a procedure using either the Sub statement or the Function statement, parentheses must be included after the name of the procedure. o Any arguments are placed inside these parentheses, separated by commas.11.4 Using Sub and Function Procedures in Codewww.ramupalanki.com
  • 28. For QTP RealTime scripts visit: www.ramupalanki.comA Function in our code must always be used on the right side of a variableassignment or in an expression.For example:Temp = Celsius(fDegrees)-Or-MsgBox "The Celsius temperature is " & Celsius(fDegrees) & " degrees."To call a Sub procedure from another procedure, type the name of the procedurealong with values for any required arguments, each separated by a comma.The Call statement is not required, but if you do use it, you must enclose anyarguments in parentheses.The following example shows two calls to the MyProc procedure. One uses the Callstatement in the code; the other doesnt. Both do exactly the same thing.Call MyProc(firstarg, secondarg)MyProc firstarg, secondargNotice that the parentheses are omitted in the call when the Call statement isntused.www.ramupalanki.com
  • 29. For QTP RealTime scripts visit: www.ramupalanki.com VB Script Built in FunctionsTypes of Functions o Conversions (25) o Dates/Times (19) o Formatting Strings (4) o Input/Output (3) o Math (9) o Miscellaneous (3) o Rounding (5) o Strings (30) o Variants (8) Important Functions1) Abs FunctionReturns the absolute value of a number.Dim numnum=abs(-50.33)msgbox num2) Array FunctionReturns a variant containing an ArrayDim AA=Array("hyderabad","chennai","mumbai")msgbox A(0)ReDim A(5)A(4)="nellore"msgbox A(4)3) Asc FunctionReturns the ANSI character code corresponding to the first letter in a string.www.ramupalanki.com
  • 30. For QTP RealTime scripts visit: www.ramupalanki.comDim numnum=Asc("A")msgbox num* It returns the value 65 *4) Chr FunctionReturns the character associated with the specified ANSI character code.Dim charChar=Chr(65)msgbox char* It returns A *5) CInt FunctionReturns an expression that has been converted to a Variant of subtype Integer.Dim numnum=123.45myInt=CInt(num)msgbox MyInt6) Date FunctionReturns the Current System Date.Dim mydatemydate=Datemsgbox mydate7) Day FunctionEx1) Dim myday myday=Day("17,December,2009") msgbox mydayEx2) Dim myday mydate=date myday=Day(Mydate) msgbox myday8) DateDiff FunctionReturns the number of intervals between two dates.Dim mydaymydate=#02-17-2009#x=Datediff("d",mydate,Now)msgbox x9) Hour FunctionReturns a whole number between 0 and 23, inclusive, representing the hour of theday.Dim mytime, Myhourmytime=Nowwww.ramupalanki.com
  • 31. For QTP RealTime scripts visit: www.ramupalanki.commyhour=hour (mytime)msgbox myhour10) Join FunctionReturns a string created by joining a number of substrings contained in an array.Dim mystring, myarray(3)myarray(0)="Chandra "myarray(1)="Mohan "myarray(2)="Tester"mystring=Join(MyArray)msgbox mystring11) Eval FunctionEvaluates an expression and returns the result.12) Time FunctionReturns a Variant of subtype Date indicating the current system time.Dim mytimemytime=Timemsgbox mytime13) VarType FunctionReturns a value indicating the subtype of a variable.Dim MyCheckMyCheck = VarType(300) Returns 2.Msgbox MycheckMyCheck = VarType(#10/19/62#) Returns 7.Msgbox MycheckMyCheck = VarType("VBScript") Returns 8.Msgbox Mycheck14) Left FunctionDim MyString, LeftStringMyString = "VBSCript"LeftString = Left(MyString, 3) LeftString contains "VBS".14) Right FunctionDim AnyString, MyStrAnyString = "Hello World" Define string.MyStr = Right(AnyString, 1) Returns "d".MyStr = Right(AnyString, 6) Returns " World".MyStr = Right(AnyString, 20) Returns "Hello World".www.ramupalanki.com
  • 32. For QTP RealTime scripts visit: www.ramupalanki.com15) Len FunctionReturns the number of characters in a string or the number of bytes required tostore a variable.Ex 1): Dim Mystring mystring=Len("Tester") msgbox mystringEx 2): Dim Mystring Mystring=Inputbox("Enter a Value") Mystring=Len(Mystring) Msgbox Mystring16) Mid FunctionReturns a specified number of characters from a string.Dim MyVarMyVar = Mid("VB Script is fun!", 4, 6)Msgbox MyVar* It Returns ‘Script’ *17) Timer FunctionReturns the number of seconds that have elapsed since 12:00 AM (midnight).Function myTime(N) Dim StartTime, EndTime StartTime = Timer For I = 1 To N Next EndTime = Timer myTime= EndTime - StartTime msgbox myTimeEnd FunctionCall myTime(2000)17) isNumeric FunctionDim MyVar, MyCheckMyVar = 53MyCheck = IsNumeric(MyVar)msgbox MyCheckMyVar = "459.95"MyCheck = IsNumeric(MyVar)msgbox MyCheckMyVar = "45 Help"MyCheck = IsNumeric(MyVar)msgbox MyCheck* It Returns True/False like Result *www.ramupalanki.com
  • 33. For QTP RealTime scripts visit: www.ramupalanki.com18) Inputbox FunctionDisplays a prompt in a dialog box, waits for the user to input text or click a button,and returns the contents of the text box.Dim InputInput = InputBox("Enter your name")MsgBox ("You entered: " & Input)19) Msgbox FunctionDisplays a message in a dialog box, waits for the user to click a button, and returns avalue indicating which button the user clicked.Dim MyVarMyVar = MsgBox ("Hello World!", 65, "MsgBox Example") VBScript syntax rules and guidelines21.1 Case-sensitivity:By default, VBScript is not case sensitive and does not differentiate between uppercase and lower-case spelling of words, for example, in variables, object and methodnames, or constants.For example, the two statements below are identical in VBScript:Browser("Mercury").Page("Find a Flight:").WebList("toDay").Select "31"browser("mercury").page("find a flight:").weblist("today").select "31"21.2 Text strings:When we enter a value as a text string, we must add quotation marks before andafter the string. For example, in the above segment of script, the names of the Website, Web page, and edit box are all text strings surrounded by quotation marks.Note that the value 31 is also surrounded by quotation marks, because it is a textstring that represents a number and not a numeric value.In the following example, only the property name (first argument) is a text stringand is in quotation marks. The second argument (the value of the property) is avariable and therefore does not have quotation marks. The third argument(specifying the timeout) is a numeric value, which also does not need quotationmarks.Browser("Mercury").Page("Find a Flight:").WaitProperty("items count", Total_Items,2000)21.3 Variables:We can specify variables to store strings, integers, arrays and objects. Usingvariables helps to make our script more readable and flexible21.4 Parentheses:www.ramupalanki.com
  • 34. For QTP RealTime scripts visit: www.ramupalanki.comTo achieve the desired result and to avoid errors, it is important that we useparentheses () correctly in our statements.21.5 Indentation:We can indent or outdent our script to reflect the logical structure and nesting of thestatements.21.6 Comments:We can add comments to our statements using an apostrophe (), either at thebeginning of a separate line, or at the end of a statement. It is recommended thatwe add comments wherever possible, to make our scripts easier to understand andmaintain.21.7 Spaces:We can add extra blank spaces to our script to improve clarity. These spaces areignored by VBScript. ErrorsWe have two types Errors in VB Script; they are VBScript Run-time Errors andVBScript Syntax Errors13.1 VBScript Run-time ErrorsVBScript run-time errors are errors that result when our VBScript script attempts toperform an action that the system cannot execute. VBScript run-time errors occurwhile our script is being executed; when variable expressions are being evaluated,and memory is being dynamic allocated.13.2 VBScript Syntax ErrorsVBScript syntax errors are errors that result when the structure of one of ourVBScript statements violates one or more of the grammatical rules of the VBScriptscripting language. VBScript syntax errors occur during the program compilationstage, before the program has begun to be executed.www.ramupalanki.com
  • 35. For QTP RealTime scripts visit: www.ramupalanki.comwww.ramupalanki.com
  • 36. For QTP RealTime scripts visit: www.ramupalanki.com File System Operations I) Working with Drives and Folders a) Creating a Folder Option Explicit Dim objFSO, objFolder, strDirectory strDirectory = "D:logs" Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFolder = objFSO.CreateFolder(strDirectory) b) Deleting a Folder Set oFSO = CreateObject("Scripting.FileSystemObject") oFSO.DeleteFolder("E:FSO") c) Copying Folders Set oFSO=createobject("Scripting.Filesystemobject") oFSO.CopyFolder "E:gcr6", "C:jvr", True d) Checking weather the folder available or not, if not creating the folder Option Explicit Dim objFSO, objFolder, strDirectory strDirectory = "D:logs" Set objFSO = CreateObject("Scripting.FileSystemObject") If objFSO.FolderExists(strDirectory) Then Set objFolder = objFSO.GetFolder(strDirectory) msgbox strDirectory & " already created " else Set objFolder = objFSO.CreateFolder(strDirectory) end if e) Returning a collection of Disk Drives Set oFSO = CreateObject("Scripting.FileSystemObject") Set colDrives = oFSO.Drives For Each oDrive in colDrives MsgBox "Drive letter: " & oDrive.DriveLetter Next f) Getting available space on a Disk Drive Set oFSO = CreateObject("Scripting.FileSystemObject") Set oDrive = oFSO.GetDrive("C:") MsgBox "Available space: " & oDrive.AvailableSpacewww.ramupalanki.com
  • 37. For QTP RealTime scripts visit: www.ramupalanki.com II) Working with Flat Files a) Creating a Flat File Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.CreateTextFile("E:ScriptLog.txt") b) Checking weather the File is available or not, if not creating the File strDirectory="E:" strFile="Scripting.txt" Set objFSO = CreateObject("Scripting.FileSystemObject") If objFSO.FileExists(strDirectory & strFile) Then Set objFolder = objFSO.GetFolder(strDirectory) Else Set objFile = objFSO.CreateTextFile("E:ScriptLog.txt") End if c) Reading Data character by character from a Flat File Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile("E:gcr.txt", 1) Do Until objFile.AtEndOfStream strCharacters = objFile.Read(1) msgbox strCharacters Loop d) Reading Data line by line from a Flat File Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile("E:gcr.txt", 1) Do Until objFile.AtEndOfStream strCharacters = objFile.Readline msgbox strCharacters Loop e) Reading data from a flat file and using in data driven testing Dim fso,myfile Set fso=createobject("scripting.filesystemobject") Set myfile= fso.opentextfile ("F:gcr.txt",1) myfile.skipline While myfile.atendofline <> True x=myfile.readline s=split (x, ",") SystemUtil.Run "C:Program FilesMercury InteractiveQuickTest Professionalsamplesflightappflight4a.exe","","C:Program FilesMercury InteractiveQuickTest Professionalsamplesflightapp","open"www.ramupalanki.com
  • 38. For QTP RealTime scripts visit: www.ramupalanki.com Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set s(0) Dialog("Login").WinEdit("Password:").SetSecure s(1) Dialog("Login").WinButton("OK").Click Window("Flight Reservation").Close Wend f) Writing data to a text file Dim Stuff, myFSO, WriteStuff, dateStamp dateStamp = Date() Stuff = "I am Preparing this script: " &dateStamp Set myFSO = CreateObject("Scripting.FileSystemObject") Set WriteStuff = myFSO.OpenTextFile("e:gcr.txt", 8, True) WriteStuff.WriteLine(Stuff) WriteStuff.Close SET WriteStuff = NOTHING SET myFSO = NOTHING g) Delete a text file Set objFSO=createobject("Scripting.filesystemobject") Set txtFilepath = objFSO.GetFile("E:gcr.txt") txtFilepath.Delete() h) Checking weather the File is available or not, if available delete the File strDirectory="E:" strFile="gcr.txt" Set objFSO = CreateObject("Scripting.FileSystemObject") If objFSO.FileExists(strDirectory & strFile) Then Set objFile = objFSO.Getfile(strDirectory & strFile) objFile.delete () End if i) Comparing two text files Dim f1, f2 f1="e:gcr1.txt" f2="e:gcr2.txt" Public Function CompareFiles (FilePath1, FilePath2) Dim FS, File1, File2 Set FS = CreateObject("Scripting.FileSystemObject") If FS.GetFile(FilePath1).Size <> FS.GetFile(FilePath2).Size Then CompareFiles = True Exit Function End If Set File1 = FS.GetFile(FilePath1).OpenAsTextStream(1, 0) Set File2 = FS.GetFile(FilePath2).OpenAsTextStream(1, 0)www.ramupalanki.com
  • 39. For QTP RealTime scripts visit: www.ramupalanki.com CompareFiles = False Do While File1.AtEndOfStream = False Str1 = File1.Read Str2 = File2.Read CompareFiles = StrComp(Str1, Str2, 0) If CompareFiles <> 0 Then CompareFiles = True Exit Do End If Loop File1.Close() File2.Close() End Function Call Comparefiles(f1,f2) If CompareFiles(f1, f2) = False Then MsgBox "Files are identical." Else MsgBox "Files are different." End If j) Counting the number of times a word appears in a file sFileName="E:gcr.txt" sString="Tester" Const FOR_READING = 1 Dim oFso, oTxtFile, sReadTxt, oRegEx, oMatches Set oFso = CreateObject("Scripting.FileSystemObject") Set oTxtFile = oFso.OpenTextFile(sFileName, FOR_READING) sReadTxt = oTxtFile.ReadAll Set oRegEx = New RegExp oRegEx.Pattern = sString oRegEx.IgnoreCase = bIgnoreCase oRegEx.Global = True Set oMatches = oRegEx.Execute(sReadTxt) MatchesFound = oMatches.Count Set oTxtFile = Nothing : Set oFso = Nothing : Set oRegEx = Nothing msgbox MatchesFound III) Working with Word Docs a) Create a word document and enter some data & save Dim objWD Set objWD = CreateObject("Word.Application") objWD.Documents.Addwww.ramupalanki.com
  • 40. For QTP RealTime scripts visit: www.ramupalanki.com objWD.Selection.TypeText "This is some text." & Chr(13) & "This is some more text" objWD.ActiveDocument.SaveAs "e:Tester.doc" objWD.Quit IV) Working with Excel Sheets a) Create an excel sheet and enter a value into first cell Dim objexcel Set objExcel = createobject("Excel.application") objexcel.Visible = True objexcel.Workbooks.add objexcel.Cells(1, 1).Value = "Testing" objexcel.ActiveWorkbook.SaveAs("f:Tester1.xls") objexcel.Quit b) Compare two excel files Set objExcel = CreateObject("Excel.Application") objExcel.Visible = True Set objWorkbook1= objExcel.Workbooks.Open("E:gcr1.xls") Set objWorkbook2= objExcel.Workbooks.Open("E:gcr2.xls") Set objWorksheet1= objWorkbook1.Worksheets(1) Set objWorksheet2= objWorkbook2.Worksheets(1) For Each cell In objWorksheet1.UsedRange If cell.Value <> objWorksheet2.Range(cell.Address).Value Then msgbox "value is different" Else msgbox "value is same" End If Next objWorkbook1.close objWorkbook2.close objExcel.quit set objExcel=nothingwww.ramupalanki.com
  • 41. For QTP RealTime scripts visit: www.ramupalanki.com Test Requirements 1) Verify Login Boundary (Check all the boundary conditions of the Login window. Checks to see if the correct message appears in the error window (Flight Reservation Message) 2) Verify Cancel Operation (in Login Dialog box, if user selects cancel button, before enter any data after enter data dialog box should be disappeared.) 3) Verify Addition, Subtraction, Multiplication and Division Operations in Calculator Application. 4) Verify state of Update Order Button, before open an Order and after open an Order (in Flight Reservation before opening an order Update Order button should be disabled after opening an order enabled.) 5) Price Consistency, In Flight Reservation (In Flight Reservation, First class price=3*Economy class price and Business class price=2*Economy class price)www.ramupalanki.com
  • 42. For QTP RealTime scripts visit: www.ramupalanki.com 6) Verify Total, In Flight Reservation (In Flight Reservation, Total = Tickets * Price) 7) Verify Flight From & Flight To Combo Boxes (In Flight reservation, select an item from Fly From: combo box and verify weather that item available or not in Fly To: combo box, like this select all items one by one in Fly From and verify weather selected items available or not in Fly To.) 8) Verify Order No Entry in Flight Reservation. (In Open Order dialog box, Order No object accepts numeric values only.) 9) Get Test Data from a Flat file and use in Data Driven Testing (through Scripting) 10) Get Test Data From a Database and use in Data Driven Testing (through Scripting) 11)Count, how many links available in Mercury Tours Home Page? 12) Count how many Buttons and Edit boxes available in Flight Reservation window?13) Verify search options in Open Order Dialog box(After selecting open order, 3 search options should be enabled and not checked,After selecting Order No option, other options should be disabled,After selecting Customer Name, Flight date option enabled and Order No disabledAfter selecting Flight date option, Customer Name enabled and Order No disabled)14) In Login Dialog box, Verify Help message (The message is ‘The password isMERCURY)15) Count all opened Browsers on desktop and close all?16) Create an Excel file, enter some data and save the file through VBscripting?For Complete Document Visit:www.ramupalanki.com
  • 43. For QTP RealTime scripts visit: www.ramupalanki.com ww.Tester.comwww.ramupalanki.com