Tuesday, January 23, 2007

About VB Script

About VBScript
VBScript is an interpreted programming language that can be embedded into an HTML web page or used in server side scripting. 
Client Side Scripting
VBScript code is executed/interpreted when an event is triggered. When the code is executed it is interpreted one line at a time. There are a number of events that will trigger the execution of a VBScript, like clicking on a form button, or the completion of a web page loading.
Note: Internet Explorer is the only browser that supports VBScript today.
Server Side Scripting
When the web server loads an .asp page from the disk into memory, it automatically knows to interpret the code in this document. Once the code has been interpreted, the resulting HTML page is sent to the browser (client) making the request.
 

In this chapter you will learn about the peculiarities of the VBScript language. These are the details for writing a script that will help you avoid errors while you are creating your own scripts and learning the basics of the VBScript programming language.
OBJECTIVES
Upon completing this section, you should be able to:
1.Placing VBScript in an HTML page and an Active Server Page
2.Case-sensitivity
3.Whitespace
4.Brackets
5.Comments
6.Variable and Function Names
7.Reserved Words
Inserting Client Side VBScript into an HTML Page
VBScript is added to an HTML page using the SCRIPT tag. The script tags should be placed inside the head tag of the document. They can appear anywhere in the document; but must be before the event that is going to trigger them. If an older browser looks at a page containing script tags it will ignore them, as older browsers are written to ignore tags they can't interpret
VBScript code should also be placed inside an HTML Comment tag set.
E.g.
When used with VBScripts the ending comment tag will also start with two slashes REM which is the VBScript code for comment. This tells the VBScript interpreter to ignore that statement.
This is a standard way for adding VBScript to your HTML pages so that it works properly for browsers that are VBScript enabled and those that do not support VBScript.


Web Page containing VBScript



           (HTML document goes here)


We may also put in a single line of code attached to an event. Events will be explained later. The general syntax for this structure is:
stuff in between the opening and closing tag
Comments:
You can create a comment using the REM command or a single quote, like this:
REM this is a comment
or
‘this is a comment
 
Continuation Character
You can continue a VBScript statement on the next line using “_”.
If x = 1 or _
   Y = 2 or _
   Z = 3 then
Multiple Statements
You can put multiple VBScript statements on one line if they are separated by full colons “:”.
X = 0 : y = 1
Reserved Words
There are a number of words that make up the components of the VBScript language. These words cannot be used for variable or function names because the program interpreter would be unable to distinguish between a default VBScript command and your variable or function name.
ABS
Erase
Lset
Sgn
and
Error
Ltrim
Sin
Array
Exit
Mid
Space
ASC
Exp
Minute
Sqr
ATN
Fix
mod
Static
Call
For
Month
Step
Cbool
Function
Next
Str
Cbyte
Hex
not
StrComp
Cdate
Hour
Nothing
String
CDbl
If
Now
Sub
Chr
imp
Null
Tan
Cint
instr
Oct
Then
Clng
Int
On
Time
Cos
is
or
Timer
Csng
IsArray
Preserve
TimeSerial
Cstr
IsDate
Private
TimeValue
CVErr
IsEmpty
Public
Trim
Date
IsNull
Randomize
Ubound
Dateserial
IsNumeric
ReDim
Ucase
Datevalue
IsObject
Rem
Until
Day
Lbound
Resume
Val
Dim
Lcase
Right
VarType
Do
Left
Rnd
WeekDay
Else
Len
Rset
Wend
Empty
Let
Rtrim
While
End
Log
Second
Xor
eqv
Loop
Set
Year
 
 
 
FALSE
 
 
 
TRUE

Declaring Your Variables
A variable is a name assigned to a location in a computer's memory to store data. Before you use a variable in a VBScript program, you should declare its name. Variables are declared with the dim keyword, like this:
dim x
dim y
dim sum
You can also declare multiple variables with the same dim keyword.
            dim x, y, sum
The initial value of the variable is empty, a special value in VBScript.
Dim is short for dimension. When you declare a variable the interpreter needs to allocate memory to hold the contents for you. In strongly typed languages (which VBScript is not) the interpreter or compiler will know what the dimension (size of memory) is required to hold the value is based on the data type. In VBScript no memory is allocated until you store a value in the variable.
Types of Variables
A big difference between VBScript and other languages like Visual Basic and C is that VBScript is untyped. This means that a VBScript variable can hold a value of any data type, and its data type does not have to be set when declaring the variable.  This allows you to change the data type of a variable during the execution of your program, for example:
dim x
x = 10
x = "ten"
 
In this example the variable x is first assigned the integer value of 10, and then the string value of the word ten.

The following is a list of data types supported by VBScript
Datatype
Description
Empty
Variant is uninitialized. Value is either 0 for numeric variables or a zero-length string ("") for string variables.
Null
Variant intentionally contains no valid data.
Boolean
Contains either True or False.
Byte
Contains integer in the range 0 to 255.
Integer
Contains integer in the range -32,768 to 32,767.
Currency
-922,337,203,685,477.5808 to 922,337,203,685,477.5807.
Long
Contains integer in the range -2,147,483,648 to 2,147,483,647.
Single
Contains a single-precision, floating-point number in the range -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values.
Double
Contains a double-precision, floating-point number in the range -1.79769313486232E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values.
Date (Time)
Contains a number that represents a date between January 1, 100 to December 31, 9999.
String
Contains a variable-length string that can be up to approximately 2 billion characters in length. ie. "The quick brown fox jumped over the lazy brown dog."
Object
Contains an object.
Error
Contains an error number.

Using Operators
Operators are the things that act on variables. We have already seen an operator used in the previous example, where we were assigning values to our variables. The example used one of the most common operators, "=" or the assignment operator. Another operator would be the addition operator "+".
            dim x, y, sum
x = 1: y = 3: sum = 0
            sum = x + y
This small chunk of VBScript code will declare the variables x, y and sum and assign the number 1 to x, 3 to y and 0 to sum. The next line of the script will add x to y and assign it to sum. The value of the sum variable will be 4.
Other operators are used to compare things, i.e. "=" equality, ">" greater than. For example,
if ( sum = 0 ) then
sum = x + y
end if
This bit of code first checks to see if sum is equal to zero, and if so then it adds x and y together and assigns the result to sum. The "if" statement is an example of a control structure which we will examine shortly.
 
 

Control Structures (Loops and Branches)
Branches
if
The "if" statement is a fundamental control statement. It allows your program to perform a test, and act based on the results of that test. For example:
            if ( (x  = 1) and (y = 3) ) then
                        sum = y - x
            end if
In this statement the value of the x variable is compared to 1 to see if it is equal, and the value of the y variable is compared with 3 to see if it is equal. The use of the “and” operator, adds an additional logical condition that says that the first comparison must be true and the second comparison must be true for the overall result of the test to be true. If the test results in an overall true condition then the statements that follow the if statement will be executed. If the test results are false nothing will occur.
An additional clause you can add to the "if" statement is the "else", an example: 
            if (sum = 0) then
                        sum = x + y
            else    
                        subtotal = sum
            end if
This statement is read as: if sum equals 0 then sum equals x plus y, or else subtotal equals sum.
Nested Ifs
You can also nest your If statements. Nesting is where one statement is contained within another one. You would do this when you need to meet one condition before you test for the second one.
If (x>10) then
            If (y>5) then
                        Rem do something
            ElseIf (y>10) then
                        Rem do something else
            End if
End if
Select Case
The select case statement is handy when a variable may take on a number of values and you want to test for some of those values. The use of “select case” is shorter and easier to read than a number of "if" statements.
            Select case n
                        case 1
                        REM start here if n equals 1.
                        REM place code here
                                   
                        case 2
                        REM start here if n equals 2.
                        REM place code here
                       
                       case 3
                        REM start here if n equals 3.
                        REM place code here

                        Case else
                        REM if n is not equal to 1, 2 or 3
                        REM case else is optional

            End Select
 
A case can also take multiple values:
 
            Case 5, 10, 15
 
A case can also take strings instead of numeric values:
 
            Case “red"
Loops
A loop is a programming structure that forces the statements contained within its delimiters to execute over and over again until a condition is met at which point the loop ends.
Do while … Loop  and  do until … Loop
While a condition is true, execute one or more statements. “While loops” are especially useful when you do not know how many times you have to loop, but you know you should stop when you meet the condition.
            dim x
              x = 1
            do while x <= 10  : REM loop until x is greater               than 10 :REM until x is greaterthan 10
              x = x + 1 : REM add one to the value of x
            loop
 
            x = 1
            do until x = 10  : REM loop until x is greater than 10
                        until x is greaterthan 10            
                        x = x + 1 : REM add one to the value of x
            loop
 
 

Loops that execute at least once.
       x = 1
            do
            until x is greater than 10
            x = x + 1 : REM add one to the value of x
            loop until x = 10  : REM loop until x is greater than 10
 

For … Next
“For loops” are useful when you know exactly how many times you want the loop to execute.           
            for x = 1 to 10 : REM loop while x is <= 10
                        do something ten times
            Next

The loops normally increment by 1, you can alter increment using the “step” statement. You can change the step to be positive or negative.
i.e. for x = 0 to 10 step 2
i.e. for x = 10 to 0 step –2
Remember that your step value should increment and decrement to the final value.
Exit For
You can also exit out of a for loop before you have reached the end of the loop. The “Exit For” statement can be used with a condition, like below. 
            for x = 1 to 10 : REM loop while x is <= 10
                        REM do something ten times
                        If (sum>10) then
                                    Exit For
                        End if
            Next
 
For Each … Next
The For Each … Next statement makes working with collections easier. An easy way to think about it is; loop through all the items in a collection. It is exceptionally handy because you don’t need to determine the beginning and ending points of the collection to construct your loop. In the example below rs is the object and fields is a collection contained in that object. We will discuss collections in detail when we cover objects.           
            Dim customer_field
            For Each customer_field in rs.fields
                        Rem Display the field
            Next
 
While … Wend
While … Wend is an older loop construct. Microsoft recommends using the Do … Loop because it affords more flexibility.
            Dim X
            X = 1  
            While ( X < 10 )
                       
                        Rem do something while C < 10
 
                        X=X+1
            Wend
Functions and Procedures (Subroutines)
Functions are an important part of programming as they allow you to create chunks of code that perform a specific task. VBScript has a number of built-in functions that are part of the language. VBScript also gives you the ability to create your own functions. Your VBScript programs may be made up of one function or several functions.
Built-in:
The built in functions are there to perform a number of actions that programmers expect to be part of a programming language. Some of the built in functions include: CLng(string value), CInt(string value), Cdate (value), etc.. We will use these functions later in the course.
Programmer Created:
Subroutines that you create start with the command “sub” and are followed by the name for the subroutine. For example:
Sub subroutine_name( argument1, argument2, … )
            .
            .
            VBScript statements go here
            .
            .
End Sub
Usually the name is an indicator of the action the function is going to provide such as “checkForm”. The name is followed by a set of parenthesis and inside the parenthesis there can be a number of arguments. Arguments are the variable names that will be used for values (data) being passed to the subroutine.
 
Two ways to invoke a Subroutine
There are two ways to invoke a subroutine, the later is the preferred method as it makes the code more readable:
1.use the subroutine name followed by the arguments.
I.e. showAlertBox arg1
2.use the call statement followed by the subroutine name with the arguments in brackets.
I.e. Call showAlertBox( arg1)
Function … End Function
All functions have the ability to pass back a single value. Another way of saying this is you can pass data into a function using its arguments, and get the results out with a returned value. Functions can only return one value. In the example below the sum of two numbers is returned by the add_two_num() function. The trick to getting the function to return a value is to assign the value to a function name, see the second line in the first function below.
dim globalVar
globalVar = 1999
function add_two_num( a, b)
            add_two_num = a + b
end function
function mainProgram()
            dim x, y, total
x = 5: y = 3: total = 0
            total = add_two_num( x , y )
            alert(total)
end function
In the above example:
1.      The function mainProgram declares variables and assigns their initial values as follows -  “x” equal to 5, “y” equal to 3 and “total” equal to 0
2.      Then it calls the add_two_num function and passes in the values of x and y.
3.      In the add_two_num function the values are added together and stored in a variable named sum.
4.      The value of sum is returned back to the mainProgram function and stored in the variable named total.
5.      The value of total is then displayed to user in an alert box.
Variables declared in a function are only available while within that. These are commonly referred to as local variables. Another type of variable is a global variable. Global variables are available to all functions, and should be used with caution, as it is easy to assign the wrong value to a global variable. In the above example globalVar is a global variable because it is declared outside of all of the functions

VBScript Procedures
We have two kinds of procedures: The Sub procedure and the Function procedure.
A Sub procedure:
is a series of statements, enclosed by the Sub and End Sub statements
can perform 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 ()
Sub mysub()
some statements
End Sub
or
Sub mysub(argument1,argument2)
some statements
End Sub
A Function procedure:
is a series of statements, enclosed by the Function and End Function statements
can perform actions and can return a value
can take arguments that are passed to it by a calling procedure
without arguments, must include an empty set of parentheses ()
returns a value by assigning a value to its name
Function myfunction()
some statements
myfunction=some value
End Function
or
Function myfunction(argument1,argument2)
some statements
myfunction=some value
End Function


Call a Sub or Function Procedure
When you call a Function in your code, you do like this:
name = findname()
Here you call a Function called "findname", the Function returns a value that will be stored in the variable "name".
Or, you can do like this:
msgbox "Your name is " & findname()
Here you also call a Function called "findname", the Function returns a value that will be displayed in the message box.
When you call a Sub procedure you can use the Call statement, like this:
Call MyProc(argument)
Or, you can omit the Call statement, like this:
MyProc argument
Conditional Statements
Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this.
In VBScript we have three conditional statements:
if statement - use this statement if you want to execute a set of code when a condition is true
if...then...else statement - use this statement if you want to select one of two sets of lines to execute
if...then...elseif statement - use this statement if you want to select one of many sets of lines to execute
select case statement - use this statement if you want to select one of many sets of lines to execute

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
The first block of code will be executed if the condition is true, and the other block will be executed otherwise (if i is not equal to 10).

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


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.
Looping Statements
Very often when you write code, you want to allow the same block of code to run a number of times. You can use looping statements in your code to do this.
In VBScript we have four looping statements:
For...Next statement - runs statements a specified number of times. 
For Each...Next statement - runs statements for each item in a collection or each element of an array
Do...Loop statement - loops while or until a condition is true
While...Wend statement - Do not use it - use the Do...Loop statement instead

For...Next 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
Next
The For statement specifies the counter variable (i) and its start and end values. The Next statement increases the counter variable (i) by one.
Step Keyword
Using the Step keyword, you can increase or decrease the counter variable by the value you specify.
In the example below, the counter variable (i) is increased by two each time the loop repeats.
For i=2 To 10 Step 2
some code
Next
To decrease the counter variable, you must use a negative Step value. You must specify an end value that is less than the start value.
In the example below, the counter variable (i) is decreased by two each time the loop repeats.
For i=10 To 2 Step -2
some code
Next
Exit a For...Next
You can exit a For...Next statement with the Exit For keyword.

For Each...Next Loop
A For Each...Next loop repeats a block of code for each item in a collection, or for each element of an array.
dim cars(2)
cars(0)="Volvo"
cars(1)="Saab"
cars(2)="BMW"

For Each x in cars
document.write(x & "
")
Next


Do...Loop
You can use Do...Loop statements to run a block of code when you do not know how many repetitions you want. The block of code is repeated while a condition is true or until a condition becomes true.
Repeating Code While a Condition is True
You use the While keyword to check a condition in a Do...Loop statement.
Do While i>10
some code
Loop
If i equals 9, the code inside the loop above will never be executed.
Do
some code
Loop While i>10
The code inside this loop will be executed at least one time, even if i is less than 10.
Repeating Code Until a Condition Becomes True
You use the Until keyword to check a condition in a Do...Loop statement.
Do Until i=10
some code
Loop
If i equals 10, the code inside the loop will never be executed.
Do
some code
Loop Until i=10
The code inside this loop will be executed at least one time, even if i is equal to 10.
Exit a Do...Loop
You can exit a Do...Loop statement with the Exit Do keyword.
Do Until i=10
i=i-1
If i<10 Then Exit Do
Loop
The code inside this loop will be executed as long as i is different from 10, and as long as i is greater than 10.
Date/Time Functions
Function
Description
CDate
Converts a valid date and time expression to the variant of subtype Date
Date
Returns the current system date
DateAdd
Returns a date to which a specified time interval has been added
DateDiff
Returns the number of intervals between two dates
DatePart
Returns the specified part of a given date
DateSerial
Returns the date for a specified year, month, and day
DateValue
Returns a date
Day
Returns a number that represents the day of the month (between 1 and 31, inclusive)
FormatDateTime
Returns an expression formatted as a date or time
Hour
Returns a number that represents the hour of the day (between 0 and 23, inclusive)
IsDate
Returns a Boolean value that indicates if the evaluated expression can be converted to a date
Minute
Returns a number that represents the minute of the hour (between 0 and 59, inclusive)
Month
Returns a number that represents the month of the year (between 1 and 12, inclusive)
MonthName
Returns the name of a specified month
Now
Returns the current system date and time
Second
Returns a number that represents the second of the minute (between 0 and 59, inclusive)
Time
Returns the current system time
Timer
Returns the number of seconds since 12:00 AM
TimeSerial
Returns the time for a specific hour, minute, and second
TimeValue
Returns a time
Weekday
Returns a number that represents the day of the week (between 1 and 7, inclusive)
WeekdayName
Returns the weekday name of a specified day of the week
Year
Returns a number that represents the year

Conversion Functions
Top

Function
Description
Asc
Converts the first letter in a string to ANSI code
CBool
Converts an expression to a variant of subtype Boolean
CByte
Converts an expression to a variant of subtype Byte
CCur
Converts an expression to a variant of subtype Currency
CDate
Converts a valid date and time expression to the variant of subtype Date
CDbl
Converts an expression to a variant of subtype Double
Chr
Converts the specified ANSI code to a character
CInt
Converts an expression to a variant of subtype Integer
CLng
Converts an expression to a variant of subtype Long
CSng
Converts an expression to a variant of subtype Single
CStr
Converts an expression to a variant of subtype String
Hex
Returns the hexadecimal value of a specified number
Oct
Returns the octal value of a specified number

Format Functions
Top

Function
Description
FormatCurrency
Returns an expression formatted as a currency value
FormatDateTime
Returns an expression formatted as a date or time
FormatNumber
Returns an expression formatted as a number
FormatPercent
Returns an expression formatted as a percentage

Math Functions
Top

Function
Description
Abs
Returns the absolute value of a specified number
Atn
Returns the arctangent of a specified number
Cos
Returns the cosine of a specified number (angle)
Exp
Returns e raised to a power
Hex
Returns the hexadecimal value of a specified number
Int
Returns the integer part of a specified number
Fix
Returns the integer part of a specified number
Log
Returns the natural logarithm of a specified number
Oct
Returns the octal value of a specified number
Rnd
Returns a random number less than 1 but greater or equal to 0
Sgn
Returns an integer that indicates the sign of a specified number
Sin
Returns the sine of a specified number (angle)
Sqr
Returns the square root of a specified number
Tan
Returns the tangent of a specified number (angle)

Array Functions
Top

Function
Description
Array
Returns a variant containing an array
Filter
Returns a zero-based array that contains a subset of a string array based on a filter criteria
IsArray
Returns a Boolean value that indicates whether a specified variable is an array
Join
Returns a string that consists of a number of substrings in an array
LBound
Returns the smallest subscript for the indicated dimension of an array
Split
Returns a zero-based, one-dimensional array that contains a specified number of substrings
UBound
Returns the largest subscript for the indicated dimension of an array

String Functions
Top

Function
Description
InStr
Returns the position of the first occurrence of one string within another. The search begins at the first character of the string
InStrRev
Returns the position of the first occurrence of one string within another. The search begins at the last character of the string
LCase
Converts a specified string to lowercase
Left
Returns a specified number of characters from the left side of a string
Len
Returns the number of characters in a string
LTrim
Removes spaces on the left side of a string
RTrim
Removes spaces on the right side of a string
Trim
Removes spaces on both the left and the right side of a string
Mid
Returns a specified number of characters from a string
Replace
Replaces a specified part of a string with another string a specified number of times
Right
Returns a specified number of characters from the right side of a string
Space
Returns a string that consists of a specified number of spaces
StrComp
Compares two strings and returns a value that represents the result of the comparison
String
Returns a string that contains a repeating character of a specified length
StrReverse
Reverses a string
UCase
Converts a specified string to uppercase

Other Functions
Top

Function
Description
CreateObject
Creates an object of a specified type
Eval
Evaluates an expression and returns the result
GetLocale
Returns the current locale ID
GetObject
Returns a reference to an automation object from a file
GetRef
Allows you to connect a VBScript procedure to a DHTML event on your pages
InputBox
Displays a dialog box, where the user can write some input and/or click on a button, and returns the contents
IsEmpty
Returns a Boolean value that indicates whether a specified variable has been initialized or not
IsNull
Returns a Boolean value that indicates whether a specified expression contains no valid data (Null)
IsNumeric
Returns a Boolean value that indicates whether a specified expression can be evaluated as a number
IsObject
Returns a Boolean value that indicates whether the specified expression is an automation object
LoadPicture
Returns a picture object. Available only on 32-bit platforms
MsgBox
Displays a message box, waits for the user to click a button, and returns a value that indicates which button the user clicked
RGB
Returns a number that represents an RGB color value
Round
Rounds a number
ScriptEngine
Returns the scripting language in use
ScriptEngineBuildVersion
Returns the build version number of the scripting engine in use
ScriptEngineMajorVersion
Returns the major version number of the scripting engine in use
ScriptEngineMinorVersion
Returns the minor version number of the scripting engine in use
SetLocale
Sets the locale ID and returns the previous locale ID
TypeName
Returns the subtype of a specified variable
VarType
Returns a value that indicates the subtype of a specified variable

No comments: