Download - Introduction to VB Script
Introduction to VB Script
Presenter:
Duration: 50 min
Aim: To give an overview of the features in VB Script.
What is VBScript?•VBScript is a scripting language •A scripting language is a lightweight programming language •VBScript is a light version of Microsoft's programming language Visual Basic
How Does it Work? 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.
VBScript Features Data TypesVBScript has only one data type called a Variant. A Variant
is a special kind of data type that can contain different kinds of information, depending on how it is used.
Variant SubtypesEmpty, Null, Boolean, Byte, Integer, Currency,Long, Single, Double, Date (Time), String,Object, Error.StatementsStatements in VBS are delimited by new line character. VBScript is
case insensitive. Eg. A = A + 10
CommentsThe Single Quote(‘) character comments the rest of the line
following it. Or we can use the Rem statement.Eg. ‘This is a comment
Constants:User Defined constants are created using Const statement.Eg. Const MyString = "This is my string."
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#
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 DegreesFahrenheit
You can also declare a variable implicitly by simply using its name in your script.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
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.
ArraysArray variables are declared in the same way as scalars, except
that the declaration of an array variable uses parentheses ( ) following the variable name.
Eg. Dim A(10)
This means that A is an array containing 11 elements. The array index starts from 0.
Multi Dimensional Arrays:
You can have as many as 60 dimensions.Eg. Dim MyTable(5, 10)
Dynamic Arrays:
An array whose size changes during the time your script is running. For a dynamic array, no size or number of dimensions is placed inside the parentheses.
Eg. Dim MyArray()
ReDim AnotherArray()
To use a dynamic array, you must subsequently use ReDim to determine the number of dimensions and the size of each dimension.
Eg. ReDim MyArray(25)
The Preserve keyword preserves the contents of the array during resizing.
Eg. ReDim Preserve MyArray(30)
There is no limit to the no. of times you can resize a dynamic array.
Operators & PrecedenceArithmetic:
– Exponentiation(^), Unary Negation(-)– Multiplication(*), Division(/), Integer Division(\), Modulus(Mod)– Addition(+), Subtraction(-)– String Concatenation(&)
Comparison:– Equlity(=), Inequality(<>)– Less Than(<) , Less Than or Equal To(<=), – Greater Than(>), Greater Than or Equal To(>=)– Object Equivalence(Is)
Logical:– Logical negation(Not) – Logical conjunction(And)– Logical disjunction(Or)– Logical exclusion(Xor), – Logical equivalence(Eqv), Logical implication(Imp)
*Each operation is evaluated as it occurs from left to right.*The Is operator is an object reference comparison operator. It does not compare
objects or their values but only determines if two object references refer to the same object.
Conditional StatementsIf...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 statement
Eg. 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
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.
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.
For...NextFor 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 Sub
Result:Displays “Tove” first time,next “Jani”,next time “Hege”
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
Introduction to Regular Expressions A regular expression is a pattern of text that consists of
ordinary characters (for example, letters a through z) and special characters, known as metacharacters. The pattern describes one or more strings to match when searching a body of text. The regular expression serves as a template for matching a character pattern to the string being searched.
Metacharacters in Regular Expressions:
Quantifiers* Matches the preceding subexpression zero or more times.
Eg. 'zo*' matches "z" and "zoo"
+ Matches the preceding subexpression one or more times.
Eg. 'zo+' matches "zo" and "zoo", but not "z".
? Matches the preceding subexpression zero or one time.
Eg. 'do(es)?' matches the "do" in "do" or "does".
Regular Expression (RegExp) Object
Provides simple regular expression support in VBScript.
Properties of RegExp Object:
• Global PropertySets or returns a Boolean value indicating if a pattern should
match all occurrences in an search string or just the first.
• IgnoreCase PropertySets or returns a Boolean value that indicates if a pattern
search is case-sensitive or not.
• Pattern PropertySets or returns the regular expression pattern being searched
for. The pattern is delimited by double quotes(“).
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
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 FunctionReturns a Variant containing an array. Eg. A = Array(10,20,30) ‘returns an array
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.
Eg. Input = InputBox("Enter your name")
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
Replace FunctionReturns 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 FunctionReturns a repeating character string of the length
specified.Eg. MyString = String(5, "*") ' Returns "*****".
UCase FunctionReturns a string that has been converted to
uppercase.Eg. MyWord = UCase("Hello World") ' Returns "HELLO WORLD".
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 comparison
Dim 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
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.
LTrim-Removes spaces on the left side of a string
5.LTrim-Removes spaces on the left side of a string
6.RTrim-Removes spaces on the right side of a string