Sunday, January 1, 2012

Programming with VBScript

VBScript stands for Visual Basic scripting. This scripting language was launched by Microsoft in 1996. Initially this scripting language was developed targeting web developers. Over these years VBScript has advanced itself into many versions evolving itself into a strong language for Automation tools.

VBScript has only one data type called a Variant. A Variant is a special type of data that can contain different kinds of information, depending upon how it is used.  A Variant can contain either numeric or string information, It behaves as a number when you use it in a numeric context, that is, when you do not include the value within double quotes, and as a string when you use it in a string context, that is , when you include the value in double quotes.You can just put the kind of data you want in a Variant, and the Variant behaves in a way that is most appropriate for the data that it contains.These different categories of information that can be contained in a Variant are called subtypes.The following table shows the subtypes of data that a Variant can contain:

You can use conversion functions to convert data from one subtype to another. Ex: CBool, Cbyte,CInt etc.
The VarType and Typename functions can be used to identify the data types  of a variable.
Syntax: VarType(variable name)
            TypeName(variable name)
The VarType and TypeName functions can return one of the following values:
If the variable is an Array than VarType() returns 8192 + VarType(array_element). Example: for an array of integer VarType() will return 8192+2 = 8194.

Comments are the non executable lines of a script, comments are used in the script for better readability and maintenance. In VBScript comments can be provided in two ways.
Use '(Single Quotes) or REM

A variable is a convenient placeholder that refers to a computer memory location where you can store program information that may change during the time your script is running. There are two ways you can declare your variables:

  1. Explicit declaration: You can declare variables explicitly in your script using:

    • DIM : Variables declared with DIM at the script level are available to all procedures within the script. You can declare variables by separating each variable name with a comma.
      ex- Dim a , b ,c.At the procedure level, variables are available only within the procedure.
    • Public : Variables declared using Public statement are available to all the procedures in all scripts of all projects.
    • Private: Private variables are available only to the script in which they are declared.
  2. Implicit declaration: You can also declare a variable implicitly by simply using its name in your script. In this method directly the name of the variable is used  and a value is assigned to a variable whenever required. Formal declaration of variables is not done here.
The values that do not alter during the entire execution of the program are called as constants. These fixed values are defined in the script using the Const statement. ex- Const myname= " Armani "

Naming Restrictions
Variables names follow the standard rules for naming anything in VBScript. A variable name:
  • Must begin with alphabetic character.
  • Cannot contain a period.
  • Must not exceed 255 characters.
  • Must be unique in the scope in which it is declared.
VBScript has a full range of operators, including arithmetic operators, comparison operators, concatenation
operators and Logical operators. When several operations occur in an expression, each part is evaluated and resolved in a predetermined order called operator precedence. you can use parenthesis to override the order of precedence and force some parts of an expression to be evaluated before others. Operations within
parenthesis are always performed before those outside. Within parentheses, however , standard operator precedence is maintained.

When expression contain operators from more than one category, arithmetic operators are evaluated first, comparison operators are evaluated next and logical operators are evaluated last. Comparison operators all
have equal precedence, that is, they are evaluated in the left to right order in which they appear. Arithmetic
and Logical operators are evaluated in the following order of precedence


Conditional Statements
Conditional statements are used to control the flow of the program. These statements in the program are
    executed when certain condition is true. In VBScript we have four conditional statements:
  •     If statement: Using If statement we can execute a single or block of statements when a condition
        is true. Ex:-
                                     If  i=0 Then
                                         msgbox "Hello"
                                     End If
  • If then else: Using the conditional statement block of statements are executed. If the condition is true else alternate block of statements are executed if the condition is false. Example:-
    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=0 Then
                                         Print "Condition is True"
                                         msgbox "Hello"
                                      Print " condition is false"
                                     msgbox " Good Bye"
                             End If
  • Select Case Statement: Using this statement one of several groups of statements are executed based on the expression value. Example: You can 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
Looping statementsUsing looping statements a group of statements can be executed repeatedly. Loops are used when a statement or set of statements are to be executed repeatedly.
  1. For Loop: A For loop is used for situations when you need to do something over and over again until some condition statement fails. Ex:-

    For count=0 to 3
           Print (count)
  2. For Each Loop: It is useful when you want to go through every element in an array but you do not   know how many elements are there inside the array.Ex:-

    Dim a(2)
    a(0)= " Pen "
    a(1) =" Register"
    a(2)= " Copy"
    For Each item In a
  3. While Loop: A While Loop is a simple loop that keeps looping while something is true. Ex:-
    Dim counter
    counter =10
    While counter>0
       print (counter)
       counter = counter -1
  4. Do Loop: Do Loop is used when we 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. Ex:-

    Do While i>10

    You can use the Until keyword to check a condition in a Do Loop statement.
    Do Until i=10
     Print (i)

    If i equals 10, the code inside the loop will never be executed.

    Loop Until i=10

    The code inside this loop will be executed at least one time, even if i=10.
Procedures are a set of statements that are enclosed within a group. This group of statements perform a specific task. Once a procedure is defined it can be called from different locations in the programs as many times as required by the program. The main purpose of using procedure is to maintain modularity and re usability. In VBScript there are two types of procedures, the Sub procedure and the Function procedure.
Advantages of procedures:
  • Modularity: By dividing our scripts into procedures we can maintain and write programs by segregating the code into smaller and manageable blocks.
  • Reusable: Procedures help us to reduce the number of lines of the code by reusing the code.
  • Generalization: Once a procedure is defined it can be used by different tests.
  • Recursive: Procedures can call themselves any number of times.
Sub Procedures:  Sub procedure is a series of VBScript statements, enclosed by Sub and End Sub statements. The Sub procedure do not return any value.Procedures use two built-in function. MsgBox and InputBox, to prompt a user for some information. It then displays the results of  a calculation based on that information. Ex:-
   Sub convertTEMP()
       temp= InputBox("Please enter the temperature in degree F",1)
      MsgBox " The temperature is " &Celsius(temp) & "degrees C"

  End Sub

Function Procedures: A Function procedure is a series of VBScript statements enclosed by the Function and End Function statements. A Function Procedure is similar to to a Sub procedure but the only difference is that it can also return a value. A Function returns a value by assigning a value to its name. The return type of a Function is always a Variant.Ex:-

Function Celsius(fDegrees)
       Celsius= (fDegrees - 32) * 5/9
End Function

Scope of Procedures:
A Procedure can be scoped as private,public or default. Procedures are public by default.
  • Public: Indicates that the procedure is accessible to all other procedures in all scripts.
  • Private: indicates that the procedure is accessible only to other procedures within the script where it is declared.
  • Default: Used only with public keyword in a class block to indicate that the Function procedure is the default method for the class. An error occurs if more than Default procedure is specified in a class.
Call Statement
Call Statement is used to pas program execution control to procedure. Procedure can be called without using a call statement. In such scenarios whenever the program encounters a procedure name it will automatically pass control to the procedure. However , if you use the Call keyword to call a procedure that requires arguments, argument list must be enclosed in parentheses. if you omit the Call keyword from the procedure call, you must also omit the parentheses around argument list. example:-
Call MyProc() or MyProc

Exit Statement
The code within a procedure is executed until the last line of the procedure i.e. End statement is encountered. In instances where the user wants to exit the procedure when certain conditions are met, exit statements come into use. Exit statements when encountered within a procedure body exits the procedure unconditionally.
Syntax: Exit [Procedure]

VBScript has many built-in functions that can be used to enhance the speed of development.
  • Conversion Functions
  • String Functions
  • Array Functions
  • Date and Time Functions
  • Math Functions
  • Other Functions






VBScripting Examples

A) Write a program to find out whether the given number is Even number or Odd number?

  1. Dim num
  2. num=inputbox ("Enter a number")
  3. n = cint(n)
  4. If num mod 2=0 Then
  5. msgbox "This is a Even Number"
  6. Else
  7. msgbox "This is a Odd Number"
  8. End If
Line 1: Declare variable n.
Line 2: Displays dialog box for the user to input text , returns a string value.
Line 3: Converts input expression into an Integer and assigns that value to n.
Line 4: If the number is divided by 2 then number is an even number else it is an odd number.
Line 5: Prints if the number is an Even number
Line 7: Prints if the number is an Odd number.
Line 8: End of If statement.



B) Find the factorial of a given number.
  1. Dim N,factorial
  2. N = inputbox(" Enter the Number")
  3. N = Cint(N)
  4. duplicateNumber = N
  5. factorial = 1
  6. if N<0 Then
  7. Msgbox  (" No factorial for Negative Numbers ")
  8. elseif (N=0) or (N=1) then
  9. Msgbox (" Factorial of  " &cstr(N) + " is 1")
  10. else
  11. while N>1
  12. factorial = factorial * N
  13. N = N-1
  14. Wend
  15. Msgbox(" Factorial of " & CStr(duplicateNumber) & " is " & CStr(factorial))
  16. end if
Line 1-5: Variable declaration, assignment and Input Reading
Line 6-7: If the Number entered is a negative number then no factorial
Line 8-9: If the Number entered is 0 or 1 then factorial value is 1
Line10-13: If N>1 then factorial = factorial times N (factorial = factorial * N)
Line 15: Prints the factorial value

For input value = 5
Iteration                                  Value of N                                  Factorial
1                                                    5                                            1*5
2                                                    4                                            1*5*4
3                                                    3                                            1*5*4*3
4                                                    2                                            1*5*4*3*2

Output: Factorial of 5 is 120


C) Verify whether the given two Strings are equal.

  1. Dim string1,string2 
  2. string1 = inputbox (" enter the first string ")
  3. string2 = inputbox (" enter the second string ")
  4. MsgBox(" First string is :" +string1)
  5. MsgBox(" Second string is :" +string2)
  6. if StrComp(string1,string2) = 0 Then
  7. MsgBox ( " The Strings are Equal ")
  8. else
  9. MsgBox(" The strings are not Equal ")
  10. End if
Line 1: Declaration of variables
Line 2-3: Initialises the String
Line 4-5: Displays the given two strings
Line 6: StrComp function compares the given two strings. if the two strings are the same the StrComp function returns 0.






No comments:

Post a Comment