vbscript basics

38
Envision , Evolve, Unleash VBScript By Srinivas & Ashok

Upload: api-3835536

Post on 10-Apr-2015

1.324 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: VBScript Basics

Envision , Evolve, Unleash

VBScript

By Srinivas & Ashok

Page 2: VBScript Basics

04/11/23 2

Overview

• VBScript is a Scripting Language.

• VBScript is a Subset of VB.

• VBScript is Interpreted at Runtime.

Page 3: VBScript Basics

04/11/23 3

Pros. and Cons. of Runtime Compilation

Advantages of Runtime Compilation:Can be embedded with other types of code.

Disadvantages of Runtime Compilation :

Compilation will be slower.

Transparent code.

Syntax errors aren’t caught until runtime.

Page 4: VBScript Basics

04/11/23 4

Advantages of Using VBScript

• Good Platform coverage.

• VBScript source implementation from Microsoft is completely free of charge.

Page 5: VBScript Basics

04/11/23 5

What Can You Do with VBScript

• Can do client side validations

• Reduces load on web server by performing some validations at client side

• Can fetch data from Database.

Page 6: VBScript Basics

04/11/23 6

Data Types

Variables can hold a wide range of data: numbers,dates,text, and other more specialized categories.The different “categories “ into which values can be divided- numbers, dates, text and so on – are called data types.

Page 7: VBScript Basics

04/11/23 7

Why Data Types are Important

A programmer must declare a variable for a specific purpose, give the variable a specific name, and declare the intention to store only a specific type of data in that variable.If all the elements are neatly segmented and maintained in consistent manner.Program is likely to do without a lot of bugs.

VBScript does not have any syntax for declaring a variable

using specific data type. All the VBScript variables have the same data type, Variant

Page 8: VBScript Basics

04/11/23 8

The Variant:VBScript’s Only Data Type

• Testing for and Coercing Subtypes

• Implicit Type Coercion

• Empty and Null

• The Object Subtype

• The Error Subtype

Page 9: VBScript Basics

04/11/23 9

Arrays as Complex Data Types

• What is an Array?

• Arrays Have Dimensions

• Array Bounds and Declaring Arrays

• Accessing Arrays with Subscripts

• Looping through Arrays

• Erasing Arrays

• Using VarType() with Arrays

Page 10: VBScript Basics

04/11/23 10

What is a Variable?

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. 

Declare variables explicitly in your script using the Dim statement.

Eg. Dim Degrees Fahrenheit

You can also declare a variable implicitly by simply using its name in your script.

Page 11: VBScript Basics

04/11/23 11

Option Explicit

The Option Explicit statement is available to require explicit declaration of all variables. The Option Explicit statement should be the first statement in your script.

Variable names follow the standard rules for naming anything in VBScript. A variable name:

• Must begin with an alphabetic character. • Cannot contain an embedded period. • Must not exceed 255 characters. • Must be unique in the scope in which it is declared

Page 12: VBScript Basics

04/11/23 12

Procedures and Functions

• Procedures and Functions allow you to modularize the code in your script into the named blocks of code that perform specific function.

• Function is a named block of code that returns a value to the calling code, while a procedure is a named block of code that does not return a value to the calling code.

Page 13: VBScript Basics

04/11/23 13

Procedures and Functions

• A named block of code.• Calling Code• Returning a value

Procedure Syntax

[Public| Private] Sub Name([Arg1], [Arg2])

[code inside the procedure]

End Sub

Page 14: VBScript Basics

04/11/23 14

Procedures and Functions

• Public is by default• Rules for naming a procedure is same as that of declaring

a variable.

Function Syntax

[Public | Private] Function Name ([Arg1], [Arg2])

[Code of the function ]

End Function

Page 15: VBScript Basics

04/11/23 15

Calling Procedures and Functions

Procedure Calling :

Legal

Greet User “Bill”

Call Greet User (“Bill”)

Not legal

Greet User (“Bill”)

Call Greet User “Bill”

Page 16: VBScript Basics

04/11/23 16

Calling Procedures and Functions

Function Calling :

Returning a value

Legal

LngSum = AddNumbers(10,20)

Illegal

LngSum = AddNumbers 10,20

Not Returning a value

Page 17: VBScript Basics

04/11/23 17

Calling Procedures and Functions

Legal

Call AddNumbers(10,20)

Illegal

LngSum = Call AddNumbers(10,20)

Legal

AddNumbers 10,20

Page 18: VBScript Basics

04/11/23 18

Optional Arguments

• Procedures and Functions can have optional arguments. If an argument is optional, then you don’t have to pass anything to it.

• Built- in VBScript procedures you call (Such as MsgBox) can have optional arguments, but your own VBScript procedures cannot.

Page 19: VBScript Basics

04/11/23 19

Exiting a Procedure or Function

• A Procedure or Function will exit naturally when the last line of code inside of it done executing, However, sometimes you want to terminate a procedure sooner than that. In this case, you can use either of the statements Exit Sub (for procedure) or Exit Function (for Functions).

• The code will stop executing whenever the Exit statement appears and the flow of the code will return to the caller.

Page 20: VBScript Basics

04/11/23 20

Inbuilt features

Inbuilt Functions: The functions described below are only few of among an exhaustive list. For the full list of functions refer to VBScript Language Reference.

Array Function

Returns a Variant containing an array.

Eg. A = Array(10,20,30) ‘returns an array

InputBox Function: Displays 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.

Eg. Input = InputBox("Enter your name")  

Page 21: VBScript Basics

04/11/23 21

Built in Functions

1.Date/Time functions eg:Date,DateAdd,DateDiff,IsDate

2.Conversion functions eg:CBool,CByte,CInt,CStrt

3.Format functions eg:FormatCurrency,FormatNumber

4.Math functions eg:Int,Log,Sin

5.Array functions eg:Array,IsArray,Spilt,LBound

6.String function eg:LTrim,Rtrim,Replace,StrComp,InStr,Mid

7.Other function eg:CreateObject,GetObject,Msgbox,Inputbox,IsEmpty,IsNull,IsNumeric

Page 22: VBScript Basics

04/11/23 22

Built in Functions

Join FunctionReturns a string created by joining a number of substrings contained in an

array. Join(list[, delimiter]) The default delimiter is space.Eg. Join(myArray, “,”) ‘Returns a concantenated string of all the elements in

the array delimited by a comma .

Left FunctionReturns a specified number of characters from the left side of a string.Left(string, length) Eg. MyString = Left(“abcd”, 3) returns abc

Right FunctionReturns a specified number of characters from the right side of a string.Right(string, length) Eg. MyString = Left(“abcd”, 3) returns abc 

Page 23: VBScript Basics

04/11/23 23

Built in Functions

Replace Function:Returns a string in which a specified substring has been replaced with another substring a specified number of times.

 Eg. MyString = Replace("XXpXXPXXp", "p", "Y") ' A binary comparison starting at the beginning ‘of the string. Returns "XXYXXPXXY".

String Function:Returns a repeating character string of the length specified.

Eg. MyString = String(5, "*") ' Returns "*****".

UCase Function:Returns a string that has been converted to uppercase.

Eg. MyWord = UCase("Hello World") ' Returns "HELLO WORLD".

Page 24: VBScript Basics

04/11/23 24

Built in Functions Examples

1.InStr--Returns the position of the first occurrence of one string within another. The search begins at the first character of the string.

Eg: Dim SearchString, SearchChar, MyPos SearchString ="XXpXXpXXPXXP" ' String to search in. SearchChar = "P" ' Search for "P". MyPos = Instr(4, SearchString, SearchChar, 1) ' A textual comparison starting at position 4.

Returns 6.2.Mid-Returns a specified number of characters from a string Dim MyString MyString = "The dog jumps" ' Initialize string. Mid(MyString, 5, 3) = "fox" ' MyString = "The fox jumps". Mid(MyString, 5) = "cow" ' MyString = "The cow jumps".

3.StrComp-Compares two strings and returns a value that represents the result of the comparisonDim MyStr1, MyStr2, MyCompMyStr1 = "ABCD": MyStr2 = "abcd" ' Define variables.MyComp = StrComp(MyStr1, MyStr2, 1) ' Returns 0.if both equalMyComp = StrComp(MyStr1, MyStr2, 0) ' Returns -1. MyStr2> MyStr1MyComp = StrComp(MyStr2, MyStr1) ' Returns 1. MyStr1> MyStr24.Len-Returns the number of characters in a string

Page 25: VBScript Basics

04/11/23 25

VBScript Keywords

Empty : The Empty keyword is used to indicate an uninitialized variable value.

False: Boolean false.True: Boolean true. Nothing : The Nothing keyword in VBScript is used to

disassociate an object variable from any actual object.Eg. Set MyObject = Nothing Null: The Null keyword is used to indicate that a variable

contains no valid data.

5. LTrim-Removes spaces on the left side of a string

6.RTrim-Removes spaces on the right side of a string

Page 26: VBScript Basics

04/11/23 26

Variable Declarations and Scope

Scope and Lifetime of VariablesA variable's scope is determined by where it is declared. Variable

declared within a procedure, can be accessed only within that procedure. It has local scope and is a procedure-level variable. Variables declared outside a procedure, are visible to all the procedures in your script. This is a script-level variable, and it has script-level scope.

A variable’s scope is a boundary within which a variable is valid and accessible. The boundary within which a variable is declared is directly related to the lifetime of that variable. Script code that is executing outside of a variable’s scope cannot access that variable. There are three types of scope that a VBScript variable can have: Script- level scope, Procedure-level scope and Class-level scope.

Page 27: VBScript Basics

04/11/23 27

Variable Declarations and Scope

• There are three statements that you can use to declare variables: Dim, Private and Public.

Dim: Used at Script or Procedure levels.

(Any variable declared at script level is available to the entire script)

Private: Used at Script or Class level but not inside the procedures or functions.

Public: Used at Class or script level. More meaning for public is declaring at Class level.

Page 28: VBScript Basics

04/11/23 28

Design Strategies for Scripts and Procedures

Here are some general principles to aid you in your script designs:• Simple script files that perform one specific job with a limited amount of code

can be written as a single block of code without any procedures or functions.

• As script files become more complex, look for ways to break the logic down into subparts using, procedures, functions, and / or classes.

• As you break the logic into subparts, keep the coordinating code at the top of the script file.

• Design each procedure and function so that it has very specific job and so that it does only the job. Give the procedure a good descriptive name that indicates what job it does.

• If the value of a script – level variable needs to be changed, use the coordinating code at the top of the script file to make the change.

Page 29: VBScript Basics

04/11/23 29

Passing Arguments to Functions and Procedures

ByRef and ByVal

Passing arguments by reference versus passing arguments by value. As argument is defined either by reference or by value depending on how it is declared in the procedure or function definition.

A by reference argument is indicated with the ByRef Keyword, whereas a by value argument can either be indicated with the ByVal keyword or not specifying either ByRef or ByVal – that is , if you do not specify one or the other explicitly, ByVal is the default.

Page 30: VBScript Basics

04/11/23 30

Literals and Named Constants

What is a Literal?A literal is any piece of static data that appears in your code

that is not stored in a variable or named constant. Literals can be strings of text, numbers, dates, or Boolean values. For examples, the word “Hello” in the Following code is a literal.

Literals:• String literal is enclosed in quotation marks (" ").Eg A = “123”• Date literals and time literals are represented by enclosing

them in number signs (#) Eg. Const CutoffDate = #6-1-97#Example: Dim strMessage strMessage = “Hello”MsgBox strMessage

Page 31: VBScript Basics

04/11/23 31

Literals and Named Constants

• What is a Named Constant?A named constant is similar to a variable, except that its

value cannot be changed at runtime. A variable is dynamic.

A named constant is static, once defined , it cannot be changed by any code during runtime- hence the name “constant”.

Constants:User Defined constants are created using Const

statement.Eg. Const MyString = "This is my string."

Page 32: VBScript Basics

04/11/23 32

Using Named constants in place of Literals

• Named constants can decrease bugs• Named constants can increase clarity• Replacing the large text literal will allow user to easily

type the code.

Named Constants Rules:

Rule#1:If you are using a literal only once, it’s probably okay to use it instead of creating a named constant.

Rule#2: If using the constant in place of a literal makes the meaning of the code more clear, use the constant

Page 33: VBScript Basics

04/11/23 33

Built-In VBScript Constants

Many VBScript hosts, such as windows Script Host and Active Server Pages, support the use of constants that are built into VBscript.

Useful for two reasons: First, it is hard to remember all VBScript functions and procedures use as parameters and return values. Second , using named constants makes code a lot easier to read.

Page 34: VBScript Basics

04/11/23 34

Conditional Statements

If...Then...ElseTo run only one statement for a True condition, use the single-line syntax. Eg. If myDate < Now Then myDate = Now  To run more than one line of code, you must use the multiple-line (or block)

syntax. This syntax includes the End If statementEg. If value = 0 Then AlertLabel.Font.Italic = True End If  

Deciding Between Several Alternatives

Using ElseIf and Else clauses, you can control program flow based on different possibilities.

Eg. If value = 0 Then MsgBox value ElseIf value = 1 Then MsgBox value Else Msgbox "Value out of range!“ End If

Page 35: VBScript Basics

04/11/23 35

Select Case

A Select Case structure works with a single test expression that is evaluated once, at the top of the structure. The result of the expression is then compared with the values for each Case in the structure. If there is a match, the block of statements associated with that Case is executed.

Select Case payment Case "Cash" MsgBox "You are going to pay cash" Case "Visa" MsgBox "You are going to pay with visa" Case "Master" MsgBox "You are going to pay with Master" Case Else MsgBox "Unknown method of payment"End Select Case Else is similar to default and is optional.

Page 36: VBScript Basics

04/11/23 36

Looping Through Code

Do LoopsThe statements are repeated either while a condition is True or until a

condition becomes True.Eg. Do While myNum > 10 myNum = myNum – 1 counter = counter + 1 LoopEg. Do Until myNum = 10 myNum = myNum – 1 counter = counter + 1 Loop While...WendEg. while myNum <> 10 myNum = myNum – 1 counter = counter + 1 wend *Because of the lack of flexibility in While...Wend, it is recommended that

you use Do...Loop instead.

Page 37: VBScript Basics

04/11/23 37

For...Next

For loops, use a counter variable whose value increases or decreases with each repetition of the loop. You can use a For...Next statement to run a block of code, when you know how many repetitions you want. You can use a counter variable that increases or decreases with each repetition of the loop, like this:

For i=1 to 10 some code NextUsing the Step keyword, you can increase or decrease the counter variable by the value you

specify.Eg . For j = 2 To 10 Step 2 total = total + j Next Step can be any integer. Default step is 1.For Each…NextThis statement is used to iterate over a collection.Dim names(2)names(0) = "Tove"names(1) = "Jani"names(2) = "Hege"For Each x In namesMsgBox x Next End SubResult:Displays “Tove” first time,next “Jani”,next time “Hege”

Page 38: VBScript Basics

04/11/23 38

Exit Statement

You can exit a Do or a For loop by using the Exit statement.

Eg. Do until i < 100 If i = a Then Exit DoLoopEg. For I = 1 to 100 If i = a Then Exit ForNext