VBScript-Session2.ppt

31
HP Global Soft Pvt Ltd

Transcript of VBScript-Session2.ppt

Page 1: VBScript-Session2.ppt

HP Global Soft Pvt Ltd

Page 2: VBScript-Session2.ppt

Recap… Introduction to VBScript Executing VBScript Variables Data Types Data types – Functions Operators Msgbox and Inputbox functions

2

Page 3: VBScript-Session2.ppt

Agenda Control Structures

If…then If .. Then .. Else If .. Then .. Else if Select Case Statement For Next For Each .. Next Do .. While Do .. Loop While Do Until loop

Arrays Types of Arrays LBound and UBound functions Single Dimension Array Two Dimension Array

Q & A

3

Page 4: VBScript-Session2.ppt

4

Control Structures

Page 5: VBScript-Session2.ppt

Control Structures to make Decision

VBScript gives you a variety of ways to direct the flow of your code. The mechanisms used to accomplish this in VBScript are called control structures. They are called structures because you construct your code around them, much like you build and finish a house around its structure.

Control structures are like the wood beams and boards in your house that all of your rooms are built upon. You can use each control structure to make your code travel in different ways, depending on how you want the decision to be made.

A control structure is a combination of keywords in code used to make a decision that alters the flow of code the computer executes.

5

Page 6: VBScript-Session2.ppt

Branching Constructs- If..then Branching is the process of making decision in your code and

then, based on that decision, executing one block of code ,not the others.

If…then The first control structure you should know about is If…Then. The syntax for this control structure is given as If condition = True Then     ... the code that executes if the condition is satisfied End If where condition is some test you want to apply to the conditional structure. If the condition is true, the code within the If and End If statements is executed. If the condition is not true, the code within these statements is skipped over and does not get executed.

Ex: Dim student_Mark

If student_mark > 45 thenmsgbox “pass”End if

6

Page 7: VBScript-Session2.ppt

Branching Constructs- If..then..Else

when you make decisions, you want to do one thing if a condition is true, otherwise, they want to do something different .

Syntax:If condition = True Then

    ...this is the code that executes if the condition is satisfiedElse    ...this is the code that executes if the condition is not satisfiedEnd If

Ex: Dim Student_mark Student_mark = 50 If Student_mark > 45 then

msgbox “pass” Else msgbox “fail”

End If

7

Page 8: VBScript-Session2.ppt

Branching Constructs- If..then..ElseIf

You can do as many tests as you want by simply placing more ElseIf statements between the first If statement and the End If statement. The syntax of such a structure looks like this:

If condition1 = True Then    ...the code that executes for condition1

ElseIf condition2 = True Then    ...the code that executes for condition2

ElseIf condition3 = True Then    ...the code that executes for condition3

End If

8

Page 9: VBScript-Session2.ppt

Branching Constructs- Select Case Statements

In the case and cases where you have to perform a large number of tests on the same expression, you can instead use the Select statement. The Select statement often makes your code easier to read and interpret than would a long list of Else and Else If statements.Select Case test_expression    Case expression-1       ...this is the code that executes if expression-1 matches

test_expression    Case expression-2       ...this is the code that executes if expression-2 matches

test_expression    Case expression-3       ...this is the code that executes if expression-3 matches

test_expression    .    .    Case Else n       ...this is the code that executes if expression-n matches

test_expression End Select

9

Page 10: VBScript-Session2.ppt

Branching Constructs- Select Case Statements

Example:Dim numnum = Inputbox ("Enter a integer between 1 - 4")Select Case num

Case "1" msgbox ("Number is One")Case "2" msgbox ("Number is Two")Case "3" msgbox ("Number is Three")Case "4" msgbox ("Number is Four")Case Else msgbox ("It is a junk

number")End Select

10

Page 11: VBScript-Session2.ppt

Control Structures – For…Next

On occasion, you will need to write code that repeats some set of statements. Oftentimes, this will occur when you need to perform some calculation over and over or when you have to apply the same calculations or processing to more than one variable, such as changing the values in an array.

For…Next The first structure is often referred to as the For…Next

loop. The syntax for this structure is For counter = start to finish

   ...code that gets repeatedNext

11

Page 12: VBScript-Session2.ppt

Control Structures – Exiting a For…Next loop

If you ever want to break out of a loop, such as when an error occurs, you can use the Exit For statement. Usually, you break out of a loop because of a problem or some exception

Example:Dim Employee_names(3),i

Employee_names(0) = “deepak” Employee_names(1) = “Arvind” Employee_names(2) = “ashwin” Employee_names(3) = “raju” For i = 0 to 3 msgbox Employee_names(i) Next

12

Page 13: VBScript-Session2.ppt

Control Structures – For Each…Next loop

It is a special kind of loop that is specifically used for traversing collections.A collection means is a collection of data almost like an array.

Example:Dim names(2),xnames(0) = "Tove"names(1) = "Jani"names(2) = "Hege"

for each x in names Msgbox xnext

13

Page 14: VBScript-Session2.ppt

Control Structures – Do While..loopThe syntax for Do while..loop is

Do While condition    ...code within the loop goes here Loop where the condition is either true or false. As long as the condition is true, the code within the loop gets executed. Once the condition becomes false, the loop stops and the code after the loop is executed.Eg: Option ExplicitDim Again, DoubleItAgain = TrueDoubleIt = 1

Do While Again = True If MsgBox ("Current total is " & DoubleIt & ". Double it again ?",

vbYesNo) = vbYes Then DoubleIt = DoubleIt * 2 Else Again = False End If Loop

14

Page 15: VBScript-Session2.ppt

Control Structures – Do…Loop while

Sometimes, it is more desirable to put the conditional test at the bottom of the loop rather than the top. You can accomplish this using the Do…Loop While structure. This control structure takes the form

Do    ...code within the loop goes here

Loop While condition

Here the condition is tested after the code inside the loop is executed. The loop always executes at least one time because it doesn't test for the condition until after it's gone through the loop once. Then, at the end, it performs the test. If you want your loop to execute at least once regardless of the condition this is the structure to use.

15

Page 16: VBScript-Session2.ppt

Control Structures – Do…Loop whileEg:

Dim DoubleItDoubleIt = 1' Keep doubling the number as long as the user desires Do'Show current results and prompt to see if we should

continue If MsgBox("Current total is " & DoubleIt & ".

Double it again ?",vbYesNo) = vbYes ThenDoubleIt = DoubleIt * 2Again = True

Else Again = False End If

DoubleIt = DoubleIt + 1Loop While Again = True Msgbox (DoubleIt)

16

Page 17: VBScript-Session2.ppt

Control Structures – Do Until…loop This is very similar to the Do While…Loop except that rather than perform the

operations within the loop while the condition is true, it executes the operations inside the loop until the condition is true

Ex:Option Explicit

Dim Count, Score, Average, Sum, i Dim Scores(10)

Do Score = InputBox("Enter the next golf score (Press Return to quit): ") If Score <> "" Then Count = Count + 1 Scores(Count-1) = CSng(Score) 'Converts an expression to a variant of subtype Single End If Loop Until Score = "" Or Count > 9

For i = 0 to Count-1 Sum = Sum + Scores(i) Msgbox sum Next

Average = (Sum / Count)

msgbox Average

This is very similar to the Do While…Loop except that rather than perform the operations within the loop while the condition is true, it executes the operations inside the loop until the condition is true

Ex:Option Explicit

Dim Count, Score, Average, Sum, i Dim Scores(10)

Do Score = InputBox("Enter the next golf score (Press Return to quit): ") If Score <> "" Then Count = Count + 1 Scores(Count-1) = CSng(Score) 'Converts an expression to a variant of subtype Single End If Loop Until Score = "" Or Count > 9

For i = 0 to Count-1 Sum = Sum + Scores(i) Msgbox sum Next

Average = (Sum / Count)

msgbox Average

17

Page 18: VBScript-Session2.ppt

18

Arrays

Page 19: VBScript-Session2.ppt

Arrays

Array:

An array is a type of variable that ties together a series of data items and places them in a single variable.

Creating Arrays: You create arrays using the same keyword you use when

creating variables-the Dim keyword.

An array created with the Dim keyword exists as long as the procedure does and is destroyed once the procedure ends.

If you create the array in the main script, outside the procedure, the values will persist as long as the page is loaded.

19

Page 20: VBScript-Session2.ppt

Arrays

Two types of Arrays: Fixed-Length Array

You can create fixed-length arrays using the following syntax: Dim Array_Name(count - 1) where Array_Name is the name of the array and count is an integer value representing the number of containers you want the array to contain. The statement

Dim Names(19) creates an array called Names that consists of 20

containers, often called elements. Eg: Dim Names(19)

Dim iFor i = 0 to 19

     Names(i) = "Unknown"Next

20

Page 21: VBScript-Session2.ppt

Arrays

Dynamic ArraysThe benefit of a dynamic array is that if you don't know how large the array will be when you write the code, you can create code that sets or changes the size while the VBScript code is running

A dynamic array is created in the same way as a fixed array, but you don't put any bounds in the declaration.Ex: Dim Names()

ReDim:ReDim tells VBScript to "re-dimension" the array to however many elements you specify ReDim takes dimensions the same way Dim can. The syntax is Ex: ReDim Array_Name(Count - 1)

Preserve keyword: It ensures that the data you’ve already stored in an array stays there when you re-size it.

Syntax :Redim Preserve varname(dimensions of array variable)

21

Page 22: VBScript-Session2.ppt

Arrays – UBound and LBound functions

UBound:UBound is a function which determines the size of the array.

The syntax for determining size of array is:size = UBound(array_name)

where size is a variable that will contain the bound value of the array and array_name is the name of the array.

LBound:The LBound function is used with the UBound function to determine the size of an array. Use the UBound function to find the upper limit of an array dimension.Syntax: LBound(array_name[,dimension])

22

Page 23: VBScript-Session2.ppt

Arrays – Single Dimension Array

Single dimension array consists of as a list of rows with only one column.

Example:Dim framename(5)

framename(0)="Jan Egil"framename(1)="Tove"framename(2)="Hege"framename(3)="Stale"framename(4)="Kai Jim"framename(5)="Borge"

For i=0 to 5 Msgbox framename(i)

Next

23

Page 24: VBScript-Session2.ppt

Arrays – Two Dimension Array

A two dimensional array is a list of values with multiple columns and rows.

0 1 2 0 Williams Tony 404-555-67451 Carter Ron 304-345-23452 Davies Miles 343-456-34563 Hancock Herbie 234-456-34524 Shorter Wayne 456-987-1267

The Last name “Williams” is stored in subscript 0,0The first name “Miles” is stored in subscript 1,2 .The phone number “404-555-6745” is stored in subscript 2,0.

24

Page 25: VBScript-Session2.ppt

Arrays –Two Dimemsion Array

Example:Dim astrPhoneList()Dim strMsgDim lngIndexDim lngUBound

Redim Preserve astrPhoneList(2,0) ‘Add first rowastrPhoneList(0,0)=“Williams”astrPhoneList(1,0)=“Tony”astrPhoneList(2,0)=“404-345-3456”

Redim Preserve astrPhoneList(2,1) ‘Add second rowastrPhoneList(0,1)=“Carter”astrPhoneList(1,1)=“Ron”astrPhoneList(2,1)=“434-675-3216”

….ContdCopyright © 2006 RelQ Software Pvt. Ltd. All rights reserved. 25

Page 26: VBScript-Session2.ppt

Arrays –Two Dimemsion ArrayRedim Preserve astrPhoneList(2,2) ‘Add Third rowastrPhoneList(0,2)=“Davies”astrPhoneList(1,2)=“Miles”astrPhoneList(2,2)=“212-345-1236”

‘Loop through the array and display its contents lngUBound=UBound(astrPhoneList,2)strMsg=“The phone list is:” & vbNewLine & vbNewLine

For lngIndex=0 to lngUBound strMsg= strmsg & astrPhoneList(0,lngIndex) & “,” strMsg= strmsg & astrPhoneList(1,lngIndex) & “_” strMsg= strmsg & astrPhoneList(2,lngIndex) & vbNewLine

NextMsgbox strMsg

26

Page 27: VBScript-Session2.ppt

27

Ascii Table

Page 28: VBScript-Session2.ppt

28

Example 1

Option Explicit

Dim ch,TestTest = Inputbox ("Please Enter")ch = asc(Test)

If Not ((ch >= 48 And ch <= 57) Or (ch >= 65 And ch <= 90) Or (ch >= 97 And ch <= 122)) ThenMsgBox "Special Character"

ElseMsgBox “Alpha Numeric"

End If

Example 2

Dim TestTest = Inputbox("Please Enter : ")if Len(Test) = 0 then

do while Len(Test) = 0 Msgbox "Please enter Alphabet or Numeric"Test = Inputbox("Please Enter : ")Loop

Else'Msgbox TestAscEncode(Test)'ChrEncode(Test)

End If

Page 29: VBScript-Session2.ppt

29

Character to Ascii

Function AscEncode(str) Dim i Dim sAscii sAscii = "“

For i = 1 To Len(str) sAscii = sAscii + CStr(Asc(Mid(str, i, 1))) & ", “

‘The CStr function converts an expression to type String Next AscEncode = sAscii MsgBox AscEncode

End Function

Ascii to Character

Function ChrEncode(str) Dim i Dim sStr sStr = "“

For i = 1 To Len(str) Step 2 sStr = sStr + Chr(CLng(Mid(str, i, 2))) & ", “ ‘Clng Returns an expression that has been converted to a Variant of subtype Long.

Next ChrEncode = sStr MsgBox ChrEncode

End Function

Example 2 Continues…

Page 30: VBScript-Session2.ppt

30

Q & A

Page 31: VBScript-Session2.ppt

31

End of Session 2