vbscript - yola

42
1 Company Confidential 1 VBSCRIPT Prepared for: *Stars* New Horizons Certified Professional Course

Upload: others

Post on 05-Feb-2022

19 views

Category:

Documents


0 download

TRANSCRIPT

1

Company Confidential

1

VBSCRIPT

Prepared for: *Stars*

New Horizons Certified Professional

Course

2

• The Microsoft Visual Basic Scripting Edition language

(VBScript), is a simplified version of the Visual Basic and

Visual Basic for Applications family of programming

languages.

• VBScript is a Scripting language

• Used as a server-side scripting language with the

Microsoft.

Introduction

VBScript is an acronym which means Visual Basic Scripting Edition. As the name

suggests, it is a scripting language which has been developed by Microsoft. It is one

of them most active scripting language available today along with JavaScript. If you

go through the syntax of VBScript, you will observer many similarities between

VBScript syntax and Microsoft’s Visual Basic Syntax.

3

• Used as client-side scripting language for the Microsoft Internet Explorer (versions 3.0 and later).

• VBScript is the default language of Active Server Pages (ASP)

• Has ability to create your own class objects.

• Has feature like Timer function, RegExp and Match objects.

Introduction (go on with…)

Simple Example:

1. Open notepad (in case of Microsoft Windows) or any other text editor.

2. Type in the following line of codes:

<html>

<head>

</head>

<body>

<script type=”text/vbscript”>

Document.Write(“Hello world”)

</script>

</body>

</html>

4

• By using the SCRIPT element you add VBScript code to an HTML page.

• The <SCRIPT> Tag

• VBScript code is written within <SCRIPT Language=”VBScript”> .... </SCRIPT>tags.

• The LANGUAGE attribute indicates the scripting language.

• SCRIPT blocks can be used anywhere in an HTML page and can be place them in both the HEAD and BODY sections.

• Placing the code in HEAD section ensures that all code is read and decoded before calling the BODY section.

How to USE

When a VBScript is inserted into a HTML document, the Internet browser will read

the HTML and interpret the VBScript. The VBScript can be executed immediately,

or at a later event.

<script type="text/vbscript">

<!-- some statements -->

</script>

5

Example:

<HTML><HEAD><TITLE>My Company Name</TITLE>

<SCRIPT LANGUAGE="VBScript"><!--

document.write("NEW HORIZONS") --></SCRIPT>

</HEAD><BODY>

How to USE (go on with…)

Scripts in the head section: Scripts to be executed when they are called or when an event is triggered go in the head section. When you place a script in the head section you will assure that the script is loaded before anyone uses it:

<html>

<head>

<script type="text/vbscript"> some statements </script>

</head>

Scripts in the body section: Scripts to be executed when the page loads go in the body section. When you place a script in the body section it generates the content of the page:

<html>

<head>

</head>

<body>

<script type="text/vbscript"> some statements </script>

</body>

Scripts in both the body and the head section: You can place an unlimited number of scripts in your document, so you can have scripts in both the body and the head section.

<html>

<head>

<script type="text/vbscript"> some statements </script>

</head>

<body>

<script type="text/vbscript"> some statements </script>

</body>

6

• When a variable declared it reserved a space in

computer memory that can be use for storing data during

the execution of scripts.

• Store input from the user via web page.

• Save data returned from procedures and functions.

• Hold results from calculations.

Declaring Variables

A variable is a "container" for information you want to store. A variable's value can

change during the script. You can refer to a variable by name to see its value or to

change its value. In VBScript, all variables are of type variant, that can store

different types of data.

7

• Dim statement, the Public statement, and the Private

statement are used to declare variables in script,

explicitly.

• Example

DimI, j, k

Declaring Variables

Let's look at a simple VBScript example to clarify the use of variables.

Sub cmdVariables_OnClick

Dim Name

Name = InputBox("Enter your name: ")

MsgBox"The name you entered was " & Name

End Sub

8

• Must begin with a letter.

• Cannot contain a period (.)

• Cannot exceed 255 characters.

• They must be unique within the same scope.

Naming Conventions

Write Notes Here:

9

VBScript has a single data type called a variant. Variants

have the ability to store different types of data.

• Byte - Integer numbers between 0 to 255

• Boolean - True and False

• Currency - Monetary values

• Date - Date and time

• Double - Extremely large numbers with decimal points

• Empty - The value that a variant holds before being used

Variants and Subtypes

Subtype Description of Uses for Each Subtype

Byte Integer numbers between 0 to 255

Boolean True and False

Currency Monetary values

Date Date and time

Double Extremely large numbers with decimal points

Empty The value that a variant holds before being used

Error An error number

Integer Large integers between ( -32,768 and 32,767)

Long Extremely large integers (-2,147,483,648 and 2,147,483,647)

Object Objects

Null No valid data

Single Large numbers with decimal points

String Character strings

10

• Error - An error number

• Integer - Large integers between -32,768 and 32,767

• Long - Extremely large integers (-2,147,483,648 and

2,147,483,647)

• Object - Objects

• Null - No valid data

• Single - Large numbers with decimal points

• String - Character strings

Variants and Subtypes

Write Notes Here:

11

• Procedure-Level variables: -When you declare a

variable inside a procedure, the variable can only be

accessed within that procedure.

• Script-Level: -When you declare a variable outside a

procedure, the variable can only be accessed by all

procedure.

Scope/Lifetime of Variables

Lifetime of Variables

How long a variable exists is its lifetime.

When you declare a variable within a procedure, the variable can only be accessed

within that procedure. When the procedure exits, the variable is destroyed. These

variables are called local variables. You can have local variables with the same

name in different procedures, because each is recognized only by the procedure in

which it is declared.

If you declare a variable outside a procedure, all the procedures on your page can

access it. The lifetime of these variables starts when they are declared, and ends

when the page is closed.

12

Example:

<script>

dim counter ‘script level

sub cmdbutton_onclick

dim temp‘procedural level

end sub

</script>

Scope/Lifetime of Variables

The example below demonstrates both script-level and procedure-level

variables.

<SCRIPT>

Dim counter

Sub cmdButton_onClick

Dim temp

End Sub

</SCRIPT>

The variable counter is a script-level variable and can be utilized throughout the

script. The variable temp exists only within the cmdButton_onClick sub-procedure.

13

Constants

VBScript does not provide support for constants, you need

to assigning values to variables.

Example:

Const MyString = "This is my string."

Const MyAge = 49

Here, TAX_RATE is our constant.

<SCRIPT>

Dim TAX_RATE

TAX_RATE = .06

Function CalculateTaxes

CalculateTaxes = CostOfGoods * TAX_RATE

End Function

</SCRIPT>

14

A variable containing a single value is a scalar variable.

Array variable is series of related values.

Example:

Dim A(9)

To declare a dynamic array, use ReDim to determine the number of dimensions and the size of each dimension. Preserve keyword used to preserve the contents of the array as the resizing takes place.

Example:

ReDim MyArray(20)

ReDim Preserve MyArray(25)

Scalar & Array Variables

Array:

The VBScript language provides support for arrays. You declare an array using the Dim statement, just as you did with variables:

Dim States(50)

The statement above creates an array with 51 elements.

Why 51?

Because VBScript arrays are zero-based, meaning that the first array element is indexed 0 and the last is the number specified when declaring the array.

You assign values to the elements of an array just as you would a variable, but with an additional reference (the index) to the element in which it will be stored:

States(5) = "California"

States(6) = "New York“

Arrays can have multiple dimensions-VBScript supports up to 60. Declaring a two dimensional array for storing 51 states and their capitals could be done as follows:

Dim StateInfo(50,1)

To store values into this array you would then reference both dimensions.

StateInfo(18,0) = "Michigan"

StateInfo(18,1) = "Lansing“

VBScript also provides support for arrays whose size may need to change as the script is executing. These arrays are referred to as dynamic arrays. A dynamic array is declared without specifying the number of elements it will contain:

Dim Customers()

15

VBScripts Procedures

Scripts are divided into blocks called procedures. Its

advantages are:

Sub Procedures:

Is a sequence of statements, enclosed by the Sub and

End sub statements.

Perform an actions, but does not return a value

can take arguments that are passed to it by a calling

procedure.

Without arguments, must include an empty set of

parentheses ().

Example:

Sub mysub()

some statements

End Sub

OR

Sub mysub(argument1,argument2)

some statements

End Sub

16

Sub Procedure

Example :

Sub DisplayFullName()Dim FirstName, LastNameDim FullName

FullName = FirstName & " " & LastNameEnd Sub

Write Notes Here:

17

Calling a Procedure

You can call procedure from another procedure, function,

or control's event in the body section of an HTML file.

Example :

Sub Detailer()DisplayFullNameEnd Sub

Write Notes Here:

18

Passing an Argument

Sometimes a procedure needs one or more values to work

on for carrying an assignment then procedure needs a

variable called argument.

Example:

Sub CalculateArea(Radius)

Write Notes Here:

19

VBScripts Function

• A function is a sequence of statements, enclosed with Function and End Function statements.

• Can take arguments which is passed by a calling function.

• Without arguments, must include an empty set of parentheses ().

• Returns a value by assigning a value to its name.

• The main difference between a function procedure and a sub procedure is that a function can return a value.

Example:

Function myfunction()

some statements

myfunction=some value

End Function

or

Function myfunction(argument1,argument2)

some statements

myfunction=some value

End Function

20

VBScripts Function

Example:

Function CalculateArea(Radius)CalculateArea = Radius * Radius * 3.14159 End Function

21

To Call Function

If you want to use the return value of a function in an event

or another function, assign the name of the function to the

appropriate local variable. Make sure you include the

argument(s) of the function between parentheses.

Example:

number = CalculateArea(50)

Write Notes Here:

22

VBScripts Conditions

Conditional statements allow to control the flow of

execution of a script or one of its sections. Depending on

the outcome of the comparison operations and other

checking process, you can take appropriate actions.

• The VBScript language is equipped with special operators that can act on natural numbers, decimal numbers, or strings.

• Equality =

• Inequality <>

• Less Then <

Write Notes Here:

23

Decision Makers

• Using conditional statements, you can write VBScript code that makes decisions and repeats actions.

• If...Then...Else statement

• Select Case statement

• The If...Then...Else statement is used to evaluate whether a condition is True or False and depending on the result it executes one or more statements.

Write Notes Here:

24

Decision Makers

When one statement needs to execute: -

Sub FixDate()Dim myDatemyDate = #2/13/95#If myDate < Now Then myDate = NowEnd Sub

When more than one statement needs to execute: -

Sub AlertUser(value)If value = 0 ThenAlertLabel.ForeColor = vbRedAlertLabel.Font.Bold = TrueAlertLabel.Font.Italic = TrueEnd IfEnd Sub

Write Notes Here:

25

Decision Makers

To choose from several alternatives:

If...Then...Else statement used.

Sub ReportValue(value)If value = 0 ThenMsgBox valueElseIf value = 1 ThenMsgBox valueElseIf value = 2 thenMsgbox valueElseMsgbox "Value out of range!"End If

If....Then.....Else

You should use the If...Then...Else statement if you want to

execute some code if a condition is true

select one of two blocks of code to execute

If you want to execute only one statement when a condition is true, you can write the code on one line:

if i=10 Then msgbox "Hello“

There is no ..else.. in this syntax. You just tell the code to perform one action if the condition is true (in this case if i=10).

If you want to execute more than one statement when a condition is true, you must put each statement on separate lines and end the statement with the keyword "End If":

if i=10 Then msgbox "Hello" i = i+1 end If

There is no ..else.. in this syntax either. You just tell the code to perform multiple actions if the condition is true.

If you want to execute a statement if a condition is true and execute another statement if the condition is not true, you must add the "Else" keyword:

if i=10 then msgbox "Hello" else msgbox "Goodbye" end If

If....Then.....Elseif

You can use the if...then...elseif statement if you want to select one of many blocks of code to execute:

if payment="Cash" then msgbox "You are going to pay cash!" elseif payment="Visa" then msgbox "You are going to pay with visa." elseif payment="AmEx" then msgbox "You are going to pay with American Express." else msgbox "Unknown method of payment." end If

26

Select Case Statement

Select Case structure evaluates an expression once at the

top of the structure.

Example: Select CaseDocument.Form1.CardType.Options(SelectedIndex)

.TextCase "MasterCard"

DisplayMCLogoValidateMCAccount

Case "Visa"DisplayVisaLogoValidateVisaAccount

Select Case

You can also use the SELECT statement if you want to select one of many blocks of code to execute:

select case payment

case "Cash"

msgbox "You are going to pay cash"

case "Visa"

msgbox "You are going to pay with visa"

case "AmEx"

msgbox "You are going to pay with American Express"

case Else

msgbox "Unknown method of payment"

end select

This is how it works: First we have a single expression (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each Case in the structure. If there is a match, the block of code associated with that Case is executed.

27

Select Case Statement

Case "American Express"DisplayAMEXCOLogoValidateAMEXCOAccount

Case ElseDisplayUnknownImagePromptAgain

End Select

Write Notes Here:

28

Loops

The "loops" enable your program to continuously execute a

block of code for a given number of times, or while a given

condition is true.

• While statement

• For … Next statement

Write Notes Here:

29

While Loop

• While statement

The VBScript While Loop executes code While a condition

is true.

Example:

Dim hoursWorkedhoursWorked = 0While hoursWorked <= 8document.write("Hours worked: " & hoursWorked)document.write("")hoursWorked = hoursWorked + 1Wend

Write Notes Here:

30

For Loop

• For Loop

The VBScript For Loop allows you to execute code for

a given number of iterations

Example:

For hoursWorked = 0 to 8

document.write("Hours worked: " & hoursWorked)

document.write("<br />")

Next

Write Notes Here:

31

Each Loop

• For Each Loop

The VBScript For Each Loop allows you to iterate over an

array. This can be a quick and easy way of accessing all

elements within an array without you needing to know how

many elements are in it.

Example:Dim shoppingList(3)shoppingList(0) = "Bananas"shoppingList(1) = "Bread"shoppingList(2) = "Pasta"For Each listItem In shoppingList

document.write(listItem)document.write("<br />")

Next

Write Notes Here:

32

VBScripts and Forms

In this section you will learn about How to use VBScript with

Forms i.e. how to validate and submit the data to the web

server.

The process to validate the forms are as under. The two

things should be checked.

1. All of the required data is entered.

2. The data entered is valid or not.

You will learn this by an example.

Write Notes Here:

33

VBScripts and Forms (go on with..)

Example:

<HTML><HEAD><TITLE>Simple Validation</TITLE><SCRIPT LANGUAGE="VBScript"> <!--Sub Submit_OnClickDim TheFormSet TheForm = Document.ValidFormIf IsNumeric(TheForm.Text1.Value) Then

If TheForm.Text1.Value < 1 Or TheForm.Text1.Value > 10 Then

MsgBox "Please enter a number between 1 and 10."

Write Notes Here:

34

VBScripts and Forms (go on with..)

Else

MsgBox "Thank you."

End If

Else

MsgBox "Please enter a numeric value."

End If

End Sub

-->

</SCRIPT>

Write Notes Here:

35

VBScripts and Forms (go on with..)

</HEAD><BODY><H3>Simple Validation</H3><HR><FORM NAME="ValidForm">Enter a value between 1 and 10: <INPUT NAME="Text1" TYPE="TEXT" SIZE="2"><INPUT NAME="Submit" TYPE="BUTTON" VALUE="Submit">

</FORM></BODY></HTML>

Write Notes Here:

36

VBScript with Objects

VBScript provides the following objects to scripts:

– The Err object, which provides access to run-time

error information.

– The RegExp object, which matches strings against

special text patterns, called regular expressions.

– The Dictionary object, which provides an item

indexing facility.

Write Notes Here:

37

The Err Object--

The Err object is a predefined global object-it does not need

to be declared before it can be used. The object is used to

encapsulate all the information relating to an error condition.

This information is presented as a series of properties, as

follows:

• The .Number property is the error number (or code) for

the error. This is the default property of the Err object.

• The .Source property contains a string that specifies the

source of the error, typically the ProgID (Programmatic

Identifier) of the object that generated the error.

Err Object

Write Notes Here:

38

Err Object (go on with…)

• The .Description property contains a string describing

the error.

• The .HelpFile and .HelpContext properties store

information to reference a help topic in a help file. This

allows the error to refer the user to information on

possible causes of the error.

To generate a user-defined run-time error, first clear the Err

object using the .Clear method, and then raise the error

using the .Raise method.

Write Notes Here:

39

The RegExp Object--

• The RegExp object provides a far more sophisticated string searching facility by using regular expressions.

• A regular expression is a string that describes a match pattern.

• The match pattern provides a template that can be used to test another string, the search string, for a matching sub-string. In its simplest form, the match pattern string is just a sequence of characters that must be matched.

RegExp Object

Write Notes Here:

40

To test a search string against a match pattern, create a

RegExp object and set the match pattern. Then use the

.Test method to test for a match.

Example:

Dim oRE, bMatchSet oRE = New RegExpoRE.Pattern = "fred“

bMatch = oRE.Test("His name was fred brown")

RegExp Object (go on with…)

Write Notes Here:

41

The Dictionary Object –

The Dictionary object is used to hold a set of data values in

the form of (key, item) pairs.

A dictionary is sometimes called an associative array

because it associates a key with an item. The keys behave

in a way similar to indices in an array, except that array

indices are numeric and keys are arbitrary strings. Each

key in a single Dictionary object must be unique.

Example:

Dim oDict

Set oDict = CreateObject("Scripting.Dictionary")

Dictionary Object

Write Notes Here:

42

Classification : Confidential

Thank You