Wednesday, December 15, 2010

VB Script Procedures

In VBScript, there are two kinds of procedures; the Sub procedure and the Function procedure.

11.1 Sub Procedures

A Sub procedure is a series of VBScript statements (enclosed by Sub and End Sub statements) that perform actions but don't return a value.

A Sub procedure can take arguments (constants, variables, or expressions that are passed by a calling procedure).

If a Sub procedure has no arguments, its Sub statement must include an empty set of parentheses ().

Syntax:

Sub Procedure name ()

Statements

-----------

-----------

End Sub

Or

Sub Procedure name (argument1, argument2)

Statements

-----------

-----------

End Sub

Example: 1

Sub ConvertTemp()

temp = InputBox("Please enter the temperature in degrees F.", 1)

MsgBox "The temperature is " & Celsius(temp) & " degrees C."

End Sub

Example: 2

11.2 Function Procedures

A Function procedure is a series of VBScript statements enclosed by the Function and End 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 that are passed to it by a calling procedure).

If a Function procedure has no arguments, its Function statement must include an empty set of parentheses.

A Function returns a value by assigning a value to its name in one or more statements of the procedure. The return type of a Function is always a Variant.

Syntax:

Function Procedure name ()

Statements

-----------

-----------

End Function

Or

Function Procedure name (argument1, argument2)

Statements

-----------

-----------

End Function

Example: 1

Function Celsius(fDegrees)

Celsius = (fDegrees - 32) * 5 / 9

End Function

Example: 2

Function cal(a,b,c)

cal = (a+b+c)

End Function

11.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 Code

A Function in our code must always be used on the right side of a variable assignment 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 procedure along 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 any arguments in parentheses.

The following example shows two calls to the MyProc procedure. One uses the Call statement in the code; the other doesn't. Both do exactly the same thing.

 
Call MyProc(firstarg, secondarg)
 
MyProc firstarg, secondarg
 

Notice that the parentheses are omitted in the call when the Call statement isn't used.

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:

  • Do...Loop: Loops while or until a condition is True.
  • While...Wend: Loops while a condition is True.
  • For...Next: Uses a counter to run statements a specified number of times.
  • For Each...Next: Repeats a group of statements for each item in a collection or each element of an array.
9.1 Using Do Loops

We can use Do...Loop statements to run a block of statements an indefinite number of times. The statements are repeated either while a condition is True or until a condition becomes True.

9.1.1 Repeating Statements While a Condition is True

Repeats a block of statements while a condition is True or until a condition becomes True

a) Do While  condition
    Statements
    -----------                 
    -----------
    Loop 

Or, we can use this below syntax:

 

Example:

 
Dim x
Do While x<5 x="x+1
            Msgbox "Hello G.C.Reddy"
            Msgbox "Hello QTP"
Loop
 
b) Do 
    Statements
    -----------                 
    -----------
    Loop While  condition
 

Example:

 
Dim x
x=1
Do  
 Msgbox "Hello G.C.Reddy"
 Msgbox "Hello QTP"
  x=x+1
Loop While x<5
 

9.1.2 Repeating a Statement Until a Condition Becomes True

 
c) Do Until  condition
    Statements
    -----------                 
    -----------
    Loop 

Or, we can use this below syntax:

Example:

 
Dim x
Do Until x=5 x=x+1
 Msgbox "G.C.Reddy"
 Msgbox "Hello QTP"
Loop

Or, we can use this below syntax:

d) Do 
    Statements
    -----------                 
    -----------
    Loop Until condition

Or, we can use this below syntax:

 

Example:

 

Dim x

x=1

Do

Msgbox "Hello G.C.Reddy"

Msgbox "Hello QTP"

x=x+1

Loop Until x=5

 

9.2 While...Wend Statement

Executes a series of statements as long as a given condition is True.

Syntax:
While  condition
    Statements
    -----------                 
    -----------                      
Wend
Example:

Dim x

x=0

While x<5 x=x+1

msgbox "Hello G.C.Reddy"

msgbox "Hello QTP"

Wend

9.3 For...Next Statement

Repeats a group of statements a specified number of times.

Syntax:

For counter = start to end [Step step]

statements

Next

Example:

Dim x

For x= 1 to 5 step 1

Msgbox "Hello G.C.Reddy"

Next

9.4 For Each...Next Statement

Repeats a group of statements for each element in an array or collection.

Syntax:

For Each item In array

Statements

Next

Example:

Dim a,b,x (3)

a=20

b=30

x(0)= "Addition is "& a+b

x(1)="Substraction is " & a-b

x(2)= "Multiplication is " & a*b

x(3)= "Division is " & a/b

For Each element In x

msgbox element

Next

Example:

MyArray = Array("one","two","three","four","five")
For Each element In MyArray
msgbox element
Next

We can control the flow of our script with conditional statements and looping statements.

Using conditional statements, we can write VBScript code that makes decisions and repeats actions. The following conditional statements are available in VBScript:

1) If…Then…Else Statement

2) Select Case Statement 
 

8.1 Making Decisions Using If...Then...Else

The If...Then...Else statement is used to evaluate whether a condition is True or False 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 compare one value or variable with another.
 
If...Then...Else statements can be nested to as many levels as you need.
 

8.1.1 Running a Statements if a Condition is True (single statement)

To run only one statement when a condition is True, use the single-line syntax for the If...Then...Else statement.

 
Dim myDate
    myDate = #2/13/98#

    If myDate < mydate =" Now "



8.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 x
x= 20
If x>10  Then

            msgbox "Hello QTP Inside"
            msgbox "x value is: "&x
            msgbox "Bye Bye"
End If
 

8.1.3 Running Certain Statements if a Condition is True and Running Others if a Condition is False

 

We can use an If...Then...Else statement to define two blocks of executable statements: one block to run if the condition is True, the other block to run if the condition is False.

Example:
 
Dim x
x= Inputbox (" Enter a value")
If x>100  Then

            Msgbox "Hello QTP Inside"
            Msgbox "X is a Big Number"
            Msgbox "X value is: "&X
Else 
            Msgbox "GCR"
    Msgbox "X is a Small Number"
   Msgbox "X value is: "&X
End If
 

8.1.4 Deciding Between Several Alternatives

A variation on the If...Then...Else statement allows us to choose from several alternatives. Adding ElseIf clauses expands the functionality of the If...Then...Else statement so we can control program flow based on different possibilities.

Example:

Dim x
x= Inputbox (" Enter a value")
 
If x>0 and x<=100 Then
            Msgbox "Hello QTP Inside"
            Msgbox "X is a Small Number"
            Msgbox  "X value is "&x
 
Else 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 QTP Inside"
            Msgbox "X is a Large Number"
 
Else 
            Msgbox "Hello Sir"
            Msgbox "X is a Grand Number"
End If
End If
End If
 

8.1.5 Executing a certain block of statements when two / more conditions are True (Nested If...)

 
Example:

Dim State, Region
State=Inputbox ("Enter a State")
Region=Inputbox ("Enter a Region")
 
If state= "AP"  Then
            If Region= "Telangana" Then
                        msgbox "Hello QTP Inside"
                        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 QTP Inside"
                        msgbox "Dist count is 9"
 
End If
End If
End If
End If
 

8.2 Making Decisions with Select Case

The Select Case structure provides an alternative to If...Then...ElseIf for selectively executing one block of statements from among multiple blocks of statements. A Select Case statement provides capability similar to the If...Then...Else statement, but it makes code more efficient and readable.

Example:

Option explicit

Dim x,y, Operation, Result

x= 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 QTP Inside"

Msgbox "Addition of x,y values is "&Result

Case "sub"

Result= x-y

Msgbox "Hello QTP Inside"

Msgbox "Substraction of x,y values is "&Result

Case "mul"

Result= x*y

Msgbox "Hello QTP Inside"

Msgbox "Multiplication of x,y values is "&Result

Case "div"

Result= x/y

Msgbox "Hello QTP Inside"

Msgbox "Division of x,y values is "&Result

Case "mod"

Result= x mod y

Msgbox "Hello QTP Inside"

Msgbox "Mod of x,y values is "&Result

Case "expo"

Result= x^y

Msgbox "Hello QTP Inside"

Msgbox"Exponentation of x,y values is "&Result

Case Else

Msgbox "Hello QTP Inside

msgbox "Wrong Operation"

End Select

 

8.3 Other Examples

 

8.3.1 Write a program for finding out whether the given year is a leap year or not?

 
Dim xyear
xyear=inputbox ("Enter Year")
 
If xyear mod 4=0 Then
            msgbox "This is a Leap year"
Else 
            msgbox "This is NOT"
End If
 

8.3.2 Write a program for finding out whether the given number is, Even number or Odd number?

Dim num

num=inputbox ("Enter a number")

If num mod 2=0 Then

msgbox "This is a Even Number"

Else

msgbox "This is a Odd Number"

End If

 

8.3.3 Read two numbers and display the sum?

 
Dim num1,num2, sum
num1=inputbox ("Enter num1")
num2=inputbox ("Enter num2")
 
            sum= Cdbl (num1) + Cdbl (num2) 'if we want add two strings conversion require
                   msgbox ("Sum is " &sum)

8.3.4 Read P,T,R values and Calculate the Simple Interest?

Dim p,t, r, si

p=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 or display Error message if the number is not a four digit number?

Dim num, sum

num=inputbox ("Enter a Four digit number")

If Len(num) = 4 Then

sum=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)

else

msgbox "Number, you entered is not a 4 digit number"

End If

8.3.6 Read any Four digit number and display the number in reverse order?

Dim num,rev

num= inputbox("Enter a number")

If len(num)=4 Then

rev=rev*10 + num mod 10

num=num/10

num= left(num,3)

rev=rev*10 + num mod 10

num=num/10

num= left(num,2)

rev=rev*10 + num mod 10

num=num/10

num= left(num,1)

rev=rev*10 + num mod 10

msgbox "Reverse Order of the number is "&rev

Else

msgbox "Number, you entered is not a 4 digit number"

End If

8.3.7 Read 4 subjects marks; calculate the Total marks and grade?

(a) If average marks Greater than or equal to 75, grade is Distinction b) If average marks Greater than or equal to 60 and less than 75 , then grade is First c) If average marks Greater than or equal to 50 and less than 60 , then grade is Second d) If average marks Greater than or equal to 40 and less than 50 , then grade is Third

e) Minimum marks 35 for any subject, otherwise 'no grade fail')

Dim e,m,p,c, tot

e=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 tot

If 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>

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>

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>

msgbox "Grade is Third"

else

msgbox "No Grade, Fail"

End If

End If

End If

End If

8.3.8 Display Odd numbers up to n?

Dim num,n

n=Inputbox ("Enter a Vaule")

For num= 1 to n step 2

msgbox num

Next

8.3.9 Display Even numbers up to n?

Dim num,n

n=Inputbox ("Enter a Vaule")

For num= 2 to n step 2

msgbox num

Next

8.3.10 display natural numers up to n and write in a text file?

Dim num, n, fso, myfile

n= inputbox ("Enter any Value")

num=1

For num= 1 to n step 1

Set fso= createobject ("scripting.filesystemobject")

set myfile=fso.opentextfile ("E:\gcr.txt", 8, true)

myfile.writeline num

myfile.close

Next

8.11 Display Natural numbers in reverse order up to n?

Dim num,n

n=Inputbox ("Enter a Vaule")

For num=n to 1 step -1

msgbox num

Next

8.12 Display Natural numbers sum up to n? (using For...Next Loop)

Dim num, n, sum

n= inputbox ("Enter a Value")

sum=0

For num= 1 to n step 1

sum= sum+num

Next

msgbox sum

8.13 Display Natural numbers sum up to n? (using While...Wend Loop)

Dim num, n, sum

n= inputbox ("Enter a Value")

While num <=cdbl (n)

sum= sum+num

num=num+1

Wend

msgbox sum

8.14 Display Natural numbers sum up to n? (using Do...Until...Loop)

Dim num, n, sum

n= inputbox ("Enter a Value")

sum=0

num=1

Do

sum= sum+num

num=num+1

Loop Until num =cdbl (n+1)

msgbox sum

8.15 Write a Function for Natural Numbers sum up to n?

Function NNumCou (n)

Dim num, sum

sum=0

For num= 1 to n step 1

sum= sum+num

Next

msgbox sum

End Function

8.16 Verify weather the entered 10 digit value is a numeric value or not?

Dim a,x,y,z,num

num=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 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 If

8.17 Verify weather the entered value is a 10 digit value or not and Numeric value or not? (using multiple if conditions)

Dim a,x,y,z,num

num=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 Then

If 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 If

End If

If len (num) <> 10 Then

Msgbox "It is NOT valid Number "

End If