VBScript Handout
VBScript Handout
Cognizant 500 Glen Pointe Center West Teaneck, NJ 07666 Ph: 201-801-0233 www.cognizant.com
VBScript
TABLE OF CONTENTS
Introduction ...................................................................................................................................7 About this Module .........................................................................................................................7 Target Audience ...........................................................................................................................7 Module Objectives ........................................................................................................................7 Pre-requisite .................................................................................................................................7 Session 1: Introduction of VBScript - Visual Basic Scripting Edition ......................................8 Learning Objectives ......................................................................................................................8 What Is VBScript?.........................................................................................................................8 Using VBScript with Internet Explorer ..........................................................................................9 Using VBScript with Internet Information Services .......................................................................9 Using VBScript with Windows Script Host ..................................................................................10 Using Visual Basic with Microsoft Access ..................................................................................11 Summary ....................................................................................................................................11 Session 2: Variant Data Type, Subtypes, and Literals .............................................................13 Learning Objectives ....................................................................................................................13 "Variant" - Data Type and Subtypes ...........................................................................................13 Data Literals ................................................................................................................................13 Data Literal Examples ................................................................................................................14 String Data Literals .....................................................................................................................15 Date and Time Data Literals .......................................................................................................16 Try It Out .....................................................................................................................................17 Summary ....................................................................................................................................18 Test your Understanding ............................................................................................................18 Exercises ....................................................................................................................................18 Session 3: Arithmetic Operations ...............................................................................................19 Learning Objectives ....................................................................................................................19 Arithmetic (+) ..............................................................................................................................19 Subtraction (-) .............................................................................................................................19 Multiplication (*) ..........................................................................................................................20 Division (/ and \) ..........................................................................................................................20 Exponents (^) ..............................................................................................................................20 Modulo Arithmetic (Mod) ............................................................................................................21 Exponentiation Operator .............................................................................................................21 Try It Out .....................................................................................................................................21
VBScript
Summary ....................................................................................................................................22 Test your Understanding ............................................................................................................22 Exercises ....................................................................................................................................22 Session 4: Numeric Comparison Operations and Logical Operations ...................................22 Learning Objectives ....................................................................................................................22 Numeric comparisons .................................................................................................................23 Logical Operations ......................................................................................................................23 Try It Out .....................................................................................................................................23 Summary ....................................................................................................................................24 Test your Understanding ............................................................................................................24 Exercises ....................................................................................................................................24 Session 5: String Operations - Concatenation and Comparison ............................................24 Learning Objectives ....................................................................................................................24 Concatenation.............................................................................................................................24 String Comparison Operations ...................................................................................................25 Try It Out .....................................................................................................................................25 Summary ....................................................................................................................................26 Exercises ....................................................................................................................................26 Session 6: Variable Declaration and Assignment Statement ..................................................26 Learning Objectives ....................................................................................................................26 Variable Declaration and "Dim" Statement ................................................................................26 Assigning Values to Variables - "=" Statement...........................................................................27 Empty - The Default Value of a Variable ....................................................................................27 Try It Out .....................................................................................................................................27 Summary ....................................................................................................................................28 Exercises ....................................................................................................................................28 Session 7: Expression and Order of Operation Precedence ...................................................29 Learning Objectives ....................................................................................................................29 What Is an Expression? ..............................................................................................................29 Try It Out .....................................................................................................................................30 Summary ....................................................................................................................................30 Test your Understanding ............................................................................................................31 Exercises ....................................................................................................................................31 Session 8: Statement Syntax and Statement Types .................................................................32 Learning Objectives ....................................................................................................................32
VBScript
What Is a Statement? .................................................................................................................32 Types of Statements ...................................................................................................................32 Summary ....................................................................................................................................33 Summary ..................................................................................... Error! Bookmark not defined. Session 9: Array Data Type and Related Statements ...............................................................34 Learning Objectives ....................................................................................................................34 What Is an Array? .......................................................................................................................34 "Dim x()" - Declaring Array Variables .........................................................................................34 "x(i)" - Accessing Array Elements with Indexes ..........................................................................35 "Dim x(n)" - Fixed-Size Array Example .......................................................................................35 "Dim x()" - Dynamic-Size Array Example ...................................................................................36 "For Each" Statement Example ..................................................................................................37 "Erase" Statement - Removing All Elements in an Array ...........................................................38 Data Type "Variant()" - Array of Variant Values .........................................................................40 Try It Out .....................................................................................................................................41 Summary ....................................................................................................................................42 Test your Understanding ............................................................................................................42 What is output for above snippet? ..............................................................................................42 Exercises ....................................................................................................................................42 Session 10: Array References and Array Assignment Statements ........................................43 Learning Objectives ....................................................................................................................43 Assigning an Array to a Scalar Variable .....................................................................................43 Array References Work Like Arrays ...........................................................................................44 Using Array () Function ...............................................................................................................45 Array Error Handling ...................................................................................................................45 Try It Out .....................................................................................................................................47 Summary ....................................................................................................................................47 Exercise ......................................................................................................................................47 Session 11: Conditional Statements - "If ... Then" and "Select Case" ...................................49 Learning Objectives ....................................................................................................................49 If Then Control Structure .........................................................................................................49 IfThen...Else ............................................................................................................................50 Deciding Between Several Alternatives .....................................................................................50 Select - Case ..............................................................................................................................51 Summary ....................................................................................................................................52 Excerise ....................................................................................... Error! Bookmark not defined.
VBScript
Session 12: Loop Statements .....................................................................................................53 Learning Objectives ....................................................................................................................53 For ... Next Statements ...............................................................................................................53 For Each. Next ........................................................................................................................53 While . . . Wend Statement .........................................................................................................54 Do Loop Statement .................................................................................................................55 Try It Out .....................................................................................................................................56 Summary ....................................................................................................................................57 Exercises ....................................................................................................................................57 Session 13: Functions and Sub Procedure ...............................................................................58 Learning Objectives ....................................................................................................................58 What is a Procedure? .................................................................................................................58 Function Call ...............................................................................................................................59 Sub Routine Call .........................................................................................................................60 Passing Arrays as Arguments ....................................................................................................60 Passing Arguments into Procedures ..........................................................................................61 Variable Scope in Procedure ......................................................................................................62 Try It Out .....................................................................................................................................64 Summary ....................................................................................................................................65 Session 14: Built In Functions ....................................................................................................66 Learning Objectives ....................................................................................................................66 Math Functions ...........................................................................................................................66 Conversion Functions .................................................................................................................66 String Functions ..........................................................................................................................67 Date and Time Functions ...........................................................................................................67 Array Functions...........................................................................................................................68 Misc. Functions ...........................................................................................................................68 Exercises ....................................................................................................................................68 Session15: Inspecting Variables Received in Procedures .....................................................69 Learning Objectives ....................................................................................................................69 Variable Inspection - Data Type Validation ................................................................................69 Session 16: Error Handling Flag and the "Err" Object .............................................................71 Learning Objectives ....................................................................................................................71 Error Handling Rules Overview ..................................................................................................71 IE Option Setting - Enable Script Debugging .............................................................................72
VBScript
You should get a dialog box with this message: ........................................................................72 "On Error Resume Next" - Turning on Error Handling................................................................73 "On Error GoTo 0" - Turning off Error Handling .........................................................................73 "Err.Number" and "Err.Clear ()" - Error Code and Clear Method ...............................................73 Built-in "Err" Object Properties and Methods .............................................................................74 "Err.Raise()" - Raising Your Own Errors.....................................................................................74 Summary ....................................................................................................................................74 Session 17: Regular Expression Pattern Match and Replacement .........................................75 Learning Objectives ....................................................................................................................75 "RegExp" Class and Object for Regular Expression Support ....................................................75 "MatchCollection" and "SubMatches" Collection Objects ...........................................................76 "Set oRegExp = New RegExp" - Creating RegExp Objects .......................................................76 Exercise ....................................................................................... Error! Bookmark not defined. Summary ....................................................................................................................................77 References ....................................................................................................................................78 Websites .....................................................................................................................................78 Books ..........................................................................................................................................78
VBScript
Introduction
About this Module
This module covers the implementation, use and generation of the VBScript.
Target Audience
This module is beneficial for the programmer and automation script developers of the functional automation tools like HP Quick Test Progression, IBM Rational Robot which support VBScript.
Module Objectives
This module will impart the knowledge of the VBScript. After completion of this module user will be able use VBScript to its core extent. User will be able to work with VBScript data types, built in functions, write user defined functions, procedures, conditional statements, conditional loops etc.
VBScript
What Is VBScript? Using VBScript with Internet Explorer Using VBScript with Internet Information Services Using VBScript with Windows Script Host Using Visual Basic with Microsoft Access
What Is VBScript?
VBScript (Visual Basic Scripting Edition) is a scripting language developed by Microsoft for Windows operating systems. A VBScript code must be executed within a host environment. It allows you to interact with the host environment to perform some programming tasks. A host environment will usually: Provide you a specific way to enter your VBScript source code. Provide you some basic objects defined in the VBScript core specification. Provide you some specific objects to let your code to interact with the host application. Provide you additional objects to let your code to access certain operating system resources. Examples of VBScript host environments Internet Explorer (IE) - Allows you to include VBScript code in HTML documents to be executed while IE is rendering HTML documents on the screen. This is also called client side scripting. Internet Information Services (IIS) - Allows you to include VBScript code in HTML documents to be executed while IIS is fetching HTML documents on the Web server to deliver to client machines. This is also called server side scripting. Windows Script Host (WSH) - Allows you to include VBScript code in script files to be executed directly on the Windows operating system. VBScript version history: 1996 VBScript 1.0 1997 VBScript 2.0 - Renamed to 5.0 later 2002 VBScript 5.6 2007 VBScript 5.7 VBScript is actually is a limited variation of Microsoft's Visual Basic programming language. Therefore VBScript shares the same language syntax as Visual Basic. Visual Basic can be used to develop stand-alone Windows applications. Visual Basic can also be used to write macro codes for other Windows applications like Microsoft Access
VBScript
VBScript
One way to add VBScript codes into your HTML documents for IIS to execute is to use the ASP (Active Server Pages) technology. If you have IIS installed on your Windows system, you can use the following steps to run a simple VBScript code in IIS. 1. Go to Control Panel, then Administrative Tools, then Internet Services Manager, and right mouse click on Default Web Site, then select properties command. 2. Click on Home Directory tab on the properties dialog box, and then click the Configuration button. 3. Click on App Mappings tab on the configuration dialog box, then check to see the following line in the mapping area to make sure that ASP is supported by IIS: Extension Executable Path Verbs .asp c:\winnt\system32\inetsrv\asp.dll GET,HEAD,POST,TRACE
4. Create the following hello.asp file: <%@ language="vbscript"%> <html><body> <% response.write ("Hello world! - VBScript in IIS") %> </body></html> 5. Copy hello.asp to \inetpub\wwwroot, which is the directory where IIS takes HTML documents. 6. Run Internet Explorer (IE) with this URL: http://localhost/hello.asp. 7. You should see "Hello world! - VBScript in IIS" on the IE window. Congratulations. You have successfully written a VBScript code for the host environment supported in IIS! What happened here was: We checked the IIS setting to ensure that ASP is supported. We created a simple ASP page - a HTML document with a simple VBScript code. The VBScript code calls the function "response.write" which is provided by the IIS host environment to insert a text string into the HTML document. We ran IE to view the resulting HTML document generated by IIS and got exactly what we expected.
10
VBScript
Hello World! - VBScript in WSH Congratulations. You have successfully written a VBScript code for the host environment provided by WSH! What happened here was: We created a simple VBScript code file. The VBScript code calls the "WScript.StdOut.WriteLine" function, which is a function provided by the WSH host environment to print a text string to the standard output channel - the command window in this case.
Summary
VBScript (Visual Basic Scripting Edition) is a scripting language derived from Visual Basic language. VBScript codes must be executed in VBScript host environments. IE (Internet Explorer) provides a VBScript host environment that allows you to do client side scripting on Web pages. IIS (Internet Information Services) provides a VBScript host environment that allows you to do server side scripting on Web pages.
11
VBScript
WSH (Windows Script Host) provides a VBScript host environment that allows you to run stand alone script code files. If you are interested to learn Visual Basic, you can write Visual Basic codes in Microsoft Access and run them as macros.
12
VBScript
Data Type and Subtypes Data Literals Data Literal Examples String Data Literals Date and Time Data Literals
Data Literals
Is a piece of code in a VBScript statement to represent a data value of a specific subtype. VBScript provides the following syntax rules for data literals of different subtypes:
13
VBScript
Byte Literal - Not exist. So there is no way to enter a Byte value into a VBScript code. If you need a Byte value, you can use the conversion function CByte() to convert an integer number value into a Byte value, like CByte(7). Integer Literal - A singed integer number within the Integer value range in decimal format, like -8, 0, and 777. Long Literal - A singed integer number within the Long value range, but outside the Integer value range, in decimal format, like -888888 and 777777. Single Literal - Not exist. So there is no way to enter a Single value into a VBScript code. If you need a Single value, you can use the conversion function CSng() to convert a real number value into a Single value, like CSng(0.00314159e30). Double: Literal - A signed real number within the Double value range in the scientific format with a decimal point and/or an exponential part, like 9.99, 0.00314159e30 and 333.333e200. Currency Literal - Not exist. So there is no way to enter a Currency value into a VBScript code. If you need a Currency value, you can use the conversion function CCur() to convert a decimal number value into a Currency value, like CCur(9.99). String Literal - A sequence of characters enclosed in double quotes ("), like "Hello". Boolean Literal - One of two keywords: True and False. Date Literal - A string representing a date and/or time enclosed in hash signs (#), #31Dec-1999#. Empty Literal - The keyword: Empty Null Literal - The keyword: Null Object Literal - Not sure. We will find out later. Error Literal - Not sure. We will find out later.
14
VBScript
String concatenation operation, "&", is used to join strings together. A special function, TypeName(), is used to show the subtype of the specified value. The statement continuation character (_) is used to join multiple lines into a single statement. Output: 7=7 : Integer CByte(7)=7 : Byte 777=777 : Integer 777777=777777 : Long 9.99=9.99 : Double CSng(9.99)=9.99 : Single 0.00314159e30=3.14159E+27 : Double 333.333e200=3.33333E+202 : Double CCur(9.99)=9.99 : Currency "Hello"=Hello : String TRUE=True : Boolean #31-Dec-1999#=12/31/1999 : Date Empty= : Empty Null= : Null The output conforms our understanding of data literal rules described in the previous section: "7=7 : Integer" shows that small integer numbers are not recognized as Byte values. "CByte(7)=7 : Byte" shows that CByte() returns a Byte value. "777777=777777 : Long" shows that large integer numbers are recognized as Long values. "9.99=9.99 : Double" shows that small real numbers are not recognized as Single values. "CSng(9.99)=9.99 : Single" shows that CSng() returns a Single value. "0.00314159e30=3.14159E+27 : Double" shows that real numbers are normalized into the standard floating-point format. "CCur(9.99)=9.99 : Currency" shows that CCur() returns a Currency value. "TRUE=True : Boolean" shows that keywords are not case sensitive. Key word "TRUE" is the same as "True". "#31-Dec-1999#=12/31/1999 : Date" shows that more than one date formats are supported. Both dd-MMM-yyyy and mm/dd/yyyy are valid. "Empty= : Empty" shows that the Empty value is converted into a blank string in a string concatenation operation. "Null= : Null" shows that the Null value is converted into a blank string in a string concatenation operation
But there is one additional rule about String data literals: If a double quote (") is part of the string, the double quote needs to be prefixed with another double quote as ("").
15
VBScript
Msgbox("Ding...") Msgbox("He said: ""Hello?""") Msgbox("She said: ""Hello, whose calling?""") Here is the output of the sample script: Ding... He said: "Hello?" She said: "Hello, whose calling?" By the way, VBScript does not support string literals with single quotes (').
16
VBScript
#21:26:00# = 9:26:00 PM #31-Dec-1999 21:26:00# = 12/31/1999 9:26:00 PM ISO format: #1999-12-31 21:26:00# = 12/31/1999 9:26:00 PM US format: #12/31/1999 9:26:00 PM# = 12/31/1999 9:26:00 PM Notice that the host environment is using the US format as the default format.
Try It Out
Code: Msgbox("#31-Dec-1999# = " & (#31-Dec-1999#)) Msgbox("#21:26:00# = " & (#21:26:00#)) ' Msgbox("#21:26:00.123# = " & (#21:26:00.123#)) Msgbox("#31-Dec-1999 21:26:00# = " _ & (#31-Dec-1999 21:26:00#)) Msgbox() Msgbox("ISO format:") Msgbox("#1999-12-31 21:26:00# = " _ & (#1999-12-31 21:26:00#)) Msgbox() Msgbox("US format:") Msgbox("#12/31/1999 9:26:00 PM# = " _ & (#12/31/1999 9:26:00 PM#))
How It Works: #31-Dec-1999# = 12/31/1999 #21:26:00# = 9:26:00 PM #31-Dec-1999 21:26:00# = 12/31/1999 9:26:00 PM ISO format: #1999-12-31 21:26:00# = 12/31/1999 9:26:00 PM US format: #12/31/1999 9:26:00 PM# = 12/31/1999 9:26:00 PM
17
VBScript
Summary
13 subtypes of Variant supported in VBScript. Data literals can be entered in VBScript statement for different subtypes in different formats. String literals must be enclosed in double quotes ("). ("") represents (") in string literals. Date literals must be enclosed in slash signs (#).
Exercises
Write the program to print todays date and current time
18
VBScript
Addition Subtraction Multiplication Division(/ and \) Exponents Modulo Arithmetic (Mod) Exponentiation Operator
Arithmetic (+)
The first arithmetic operator is the addition operator. You already used this operator yesterday and probably intuitively understood its purpose because it is so commonly used and easy to understand. The addition operator is used to add values, whether they are stored in variables, constants, or literal numbers. You also use the + operator to concatenate strings, but for now, just focus on its ability to add numbers-I'll discuss string concatenation later today. You can add variables, numbers, and constants in a variety of combinations with the addition operator. For example, you can use the addition operator to add two numbers together and assign them to a variable: Orders = 2 + 3 You can also add a number to a variable and assign it to another variable: Result = Quantity + 15 You can even add a constant to a variable and store the result in another: BoxType = vbYesNo + vbQuestion You can add as many numbers, variables, and constants as you want: Guests = Mine + 5 + His + 8 + Hers
Subtraction (-)
The subtraction operator should also be very familiar to you. This operator works the same way the addition operator does except that it subtracts one or more numbers rather than add them. Otherwise, the syntax is the same. You can subtract two numbers and assign the result to a variable: Result = 100 - 37 You can also use variables: Result = 100 - Count You can also subtract more than two values: Result = 100 - Count - Extras
19
VBScript
You can combine addition and subtraction in the same code statement: Result = May + June - July
Multiplication (*)
Addition and subtraction are important, but you also need to be able to multiply values together. In most computer languages, the * symbol is used to indicate multiplication, not the x symbol. You might be able to use x on paper, but to the computer, x is a variable, not a multiplication symbol. If you enter the command Result = 3 x 2 The interpreter will give you a syntax error. Rather, you should enter the command Result = 3 * 2 to be correct.
Division (/ and \)
The division operator is the last of the four commonly used arithmetic operators. Among the common arithmetic operators, division is the most complicated arithmetic operation a computer performs. This shouldn't surprise you if you remember learning long division in grade school math class. VBScript has two types of division operators. The first operator handles numbers with decimal points. Usually referred to as the floating-point division operator, it's represented by the / symbol in code listings. c=a/b This code divides the variable a by b and puts the result into the variable c. Similarly, you could use numbers and perform a division such as c=a/2 This, in this case, divides the variable a in half. If the variable a were set to some valid numeric value, say 3, the result stored in c would be 1.5. Integer division is performed the same way floating-point division is, but the operator is different. Rather than use a forward slash (/), you use a backward slash (\). The following code shows the syntax: Result = a \ b Returning to the t-shirt example, if you coded the bonus calculation in your script as c = 1204 / 16 You would end up with the value of 75.25 stored in variable c.
Exponents (^)
The exponent operator calculates a result based on the following formula: Result = number ^ exponent The expression Result = 2 ^ 3 Evaluates to 8 because 2 * 2 * 2 = 8. The exponent function, which is available on most scientific and business calculators, is often used in formulas relating to science, engineering, and accounting.
20
As you can see, the remainder is indeed 1. The Mod operator returns the remainder. In the expression Result = 5 Mod 2 The return variable Result is equal to 1.
Exponentiation Operator
Exponentiation is the ability to raise a number to the power of another number. This operation is expressed using the ^ operator (Shift + 6). In Microsoft Visual Basic (and Microsoft Access), this formula is written as: y^x and means the same thing. Either or both y and x can be values or expression, but they must carry valid values that can be evaluated. When the operation is performed, the value of y is raised to the power of x. You can display the result of such an operation in a field using the assignment operator as follows: =y^x You can also assign the operation to an expression as follows: Total = y^x
Try It Out
Msgbox(3.333e200 + 0.111e200)
21
VBScript
Msgbox(1.0e0 - 1.0e20) Msgbox(11.0 * 1.0e20) Msgbox(20.0e20 / 3.0e0) Msgbox(3 ^ 40) Here is the output: 3.444E+200 -1E+20 1.1E+21 6.66666666666667E+20 1.21576654590569E+19
Summary
VB supports 6 numeric operations on integers. The whole number division operator sign is (\). VB supports 5 numeric operations on floating numbers.
Exercises
What is output for below program? 2147483648 mod 2
22
Logical Operations
Logical operations are operations that: Operates on one Boolean operand or two Boolean operands. Produces a Boolean value by applying the logical operation specified by the operator. There are 4 logical operations supported in VB: Logical add (Add): Resulting (True) if both operands are (True). Logical or (Or): Resulting (True) if one of the operands is (True). Logical not (Not): Resulting (True) if the operand is (False). Logical xor (Xor): Resulting (True) if one and only one operand is (True).
Try It Out
Msgbox(1 = 1) Msgbox(1 <> 1) Msgbox(9.9999e-1 > 9.99999e-1) Msgbox(9.9999e-1 < 1) Msgbox(9.9999e-1 >= 0.99999) Msgbox(1.00000001 <= 1)
23
VBScript
True True False
Summary
VB supports 6 numeric comparisons. VB supports 4 logical operations
Exercises
What is the output for below programs? Dim x = 5, y = 6; Msgbox((x > y) || (y < x/0)) Msgbox((x < y) || (y < x/0)){ Msgbox(<>(x < y) && <>(y < x/0)){
Concatenation
Concatenation is a string operation that: Operates on two string operands. Produces a new string by concatenating the second operand to the end of the first operand. Uses (&) as the operator.
24
VBScript
See the next section for example on how concatenation works.
Try It Out
Msgbox("Hello " & "world!") Msgbox("ABC" = "abc") Msgbox("abc " > "abc") Msgbox("abc" < "abc") Msgbox("abc" >= "abd") Msgbox("abc" <= "abc") How It Works: Here is the output: Hello world! False True False False True
25
VBScript Summary
Use (&) operator to concatenate strings. String comparisons are based character ASCII values.
Exercises
What is output for the below program? Msgbox("ABC" <> "abc")
Variable Declaration and "Dim" Statement You declare variables explicitly in your script using the Dim statement, the Public statement, and the Private statement. For example: Dim DegreesFahrenheit
You declare multiple variables by separating each variable name with a comma. For example: Dim Top, Bottom, Left, Right
26
VBScript
You can also declare a variable implicitly by simply using its name somewhere in your script. That's not generally considered to be a good practice because you could misspell the variable name in one or more places, causing unexpected results when your script is run.
For that reason, 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.
B=200
Try It Out
Dim c As Byte Dim i As Integer Dim l As Long Dim f As Single Dim d As Double Dim y As Currency Dim s As String Dim b As Boolean Dim v As Variant c = 31 i = 777 l = 777777 f = 3.14159E+27 d = 3.33333E+202 y = 999999.5555 s = "Hello" b = True
27
VBScript
v = "Variant: Any data type." MsgBox (c & vbCrLf & _i & vbCrLf & _l & vbCrLf & _f & vbCrLf & _d & vbCrLf & _y & vbCrLf & _ s & vbCrLf & _ b & vbCrLf & _v & vbCrLf)
How It Works: Run the above code, you will get a message box with the following output: 31 777 777777 3.14159E+27 3.33333E+202 999999.5555 Hello True Variant: Any data type.
No surprises in the output. But I have used: A VB built-in constant, "vbCrLf", which represents special characters, "Carriage Return" and "Line Feed", to break the output message into multiple lines. "_" character to break a VB statement into multiple lines.
Summary
Two ways to declare variables: implicit and explicit. VB scripts only support "Variant" variables.
Exercises
Create a variable that holds a date and print it to the screen
28
VBScript
What Is an Expression?
Giving a precise single definition of an expression is not an easy task. So I will try to define it in a recursive way: 1. A simple expression is a presentation of a data value like, a literal, a variable, an element of an array, or a function call. 2. A complex expression is an operation represented by an operator, and one or two expressions as operands. The operation will result a data value. If you apply rule #2 recursively, an expression may contain multiple operations in a sequence. When this happens, operations must be carried out in an order defined by the following rules: A. Operations enclosed in a pair of parentheses must be carried out before operations outside the parentheses. B. Operations with higher precedence must be carried out before operations with lower precedence. C. Operation on the left must be carried out before the operation on the right side. D. Rule A must be applied before Rule B, which must be applied before Rule C.
Precedence of Operations
The following table shows you the relative precedence of some commonly used operations: Precedence Operations Notes 1 ^ Exponentiation 2 * / \ Mod Multiplication, division 3 +Addition and subtraction 4 = <> < > <= >= Comparisons 5 And Or Xor Logical operations
29
Summary
Expression always results a single value.
30
VBScript
Exercises
Explain the order of operation precedence for the below snippet year % 4 == 0 && year % 100 != 0 || year % 400 == 0
31
VBScript
What Is a Statement?
A Statement is a basic unit of VB source code. Here are some general rules about a VB statement: 1. One line cannot have more than one statement. 2. One statement is usually written in one line. If you want to continue a statement into the second line, you should put (_) at the end of the first line like this: statement_part_1 _ statement_part_2 3. Comments can be entered at the end of a statement proceeded with (') like this: statement ' comment 4. Statements are case insensitive. This means that all keywords, variable names and procedure names are case insensitive.
Types of Statements
Like any other generic programming language, VB offers lots of types of statements. I will only list some commonly uses statement types below: Assignment Statement - Assigning values to variables. Call Statement - Invoking sub procedures. Dim Statement - Defining a variable or an array. Do ... Loop Statement - Looping on dynamic conditions. Erase Statement - Erasing data from arrays. Exit Statement - Terminating loops or procedures. For Each ... Next Statement - Looping on every elements of arrays. For ... Next Statement - Looping on incremental variables. Function Statement - Defining function procedures. If Statement - Executing statement blocks conditionally. ReDim Statement - Resetting dynamic-size arrays. Rem Statement - Writing comments Select Case Statement - Executing statement blocks selectively. Sub Statement - Defining subroutine procedures. While Statement - Looping on dynamic conditions.
32
VBScript
Summary
Statements can be continued on the next line with (_) character. VB source code is case insensitive.
33
VBScript
What Is an Array? Array Variable Declaration Assigning Values to Array Elements Retrieving Values from Array Elements Fixed-Size Array Example Dynamic-Size Array Example "Array" Function and "For Each" Example "Erase" Statements
What Is an Array?
Like many other programming languages, Visual Basic supports the concept of array as a built-in data structure with the following features: An array can be used to store a collection of data elements of the same data type. The number of elements in an array can be a fixed number or can be re-adjusted dynamically. An array must be associated with a variable for referencing. Each element in an array is associated with a unique index number. By default, index number starts from 0. A specific element in an array can be referred by the index number. A number of built-in functions are provided to work with arrays. "For Each" loop statement is provided as an easy way to loop through all elements in an array. "Erase" statement is provided as a quick way to remove all values from an array.
34
VBScript
... The "Dim" statement declares an array variable without any upper bound. The "ReDim" statement resets the upper bound to a new value. The optional key word "Preserve" specifies that all old elements must be preserved when resetting the array size. Array declared in this way can be resized at any time. 3. Implicit Declaration with "Array" Function - Using "Array" function as shown in the following syntax: variable_name = Array(element_1, element_2, ...) The "Array" function takes a list of values of "Variant" type, and returns a dynamic-size array. Note that once an array is declared, all elements will have default values based. See other chapter for different default values for different data types. VB offers some other useful functions and statements for you to work with arrays: IsArray(variable_name) - Returns "True" if the specified variable is an array. UBound(array_variable) - Returns the upper bound of the specified array. LBound(array_variable) - Returns the lower bound of the specified array. "For Each" - Loops through all elements in an array. "Erase" - Removes all values from an array.
Dim aWeek(6) aWeek(0) = "Sun" aWeek(4) = "Thu" aWeek(6) = "Sat" aWeek(1) = "Mon"
Msgbox("Days in a week:") For i=LBound(aWeek) To UBound(aWeek) Msgbox (" " & i & " = " & aWeek(i))
35
VBScript
Next ' aWeek(10) = "Abc" 'Error 1: Subscription out of range ' ReDim Preserve aWeek(10) 'Error 2: This array is fixed Here is the output: Is aWeek an array? True Days in a week: 0 = Sun 1 = Mon 2= 3= 4 = Thu 5= 6 = Sat Note that there are two errors commented out in the example: Error 1 - Array index (subscription) must be in the range of lower bound and upper bound. Error 2 - Fixed-size array cannot be resized with "ReDim" statements.
36
VBScript
Check 1: Is aYear an array? True Check 2: Is aYear an array? True Months in a year: 0 = Jan 1 = Feb 2= 3= 4= 5 = Jun 6= 7= 8= 9= 10 = Nov 11 = Note that: Output message "Check 1" shows that a dynamic-size array is an array event if its size is not set yet. Commented out "Error 2" shows that UBound cannot be used are array's size is not set yet.
To show you how the "Array" function and the "For Each" statement work, see the following example Creating a dynamic array with the "Array" function aSite = Array("yahoo", "netscape", "microsoft") Msgbox("Is aSite an array? " & IsArray(aSite)) Msgbox("Lower bound of aPrime = " & LBound(aSite)) Msgbox("Upper bound of aPrime = " & UBound(aSite)) ' Resizing the array ReDim Preserve aSite(8) aSite(8) = "ibm" ' Updating array elements For Each sSite In aSite sSite = sSite & ".com" Next Retrieving array elements Msgbox("Web sites:") For Each sSite In aSite Msgbox(" " & sSite )
37
VBScript
Next
Here is the output: Is aSite an array? True Lower bound of aPrime = 0 Upper bound of aPrime = 2 Web sites: yahoo netscape microsoft
ibm The example confirms that: Arrays created with the "Array" function are dynamic-size arrays. "For Each" statement creates a copy of the current element in the temporary variable. You cannot update element values in this way. My "Updating array elements" code block updated only the temporary variable.
If the specified array is a fixed-size array, it will reset all elements to the default value. If the specified array is a dynamic-size array, it will reset the array to zero size. To show you how the "Erase" statements work, see the following example Setting a fixed-size array Dim aFixed(1) aFixed(0) = "Dog" aFixed(1) = "Cat" Msgbox("") Msgbox("Favorite pets:") For Each sItem In aFixed Msgbox(" " & sItem ) Next ' Setting a dynamic-size array aDynamic = Array("Apple", "Orange") Msgbox ("") Msgbox("Favorite fruits:")
38
VBScript
For Each sItem In aDynamic Msgbox(" " & sItem ) Next ' Erasing arrays Msgbox("") Msgbox("Erasing arrays...") Erase aFixed Erase aDynamic ' Looking at arrays again Msgbox("") Msgbox("Pets left:") iCount = 0 For Each sItem In aFixed iCount = iCount + 1 Msgbox(" " & sItem ) Next Msgbox(" Count = " & iCount) Msgbox("") Msgbox("Fruits left:") iCount = 0 For Each sItem In aDynamic iCount = iCount + 1 Msgbox(" " & sItem ) Next Msgbox(" Count = " & iCount)
39
VBScript
40
VBScript
& TypeName(anArray(0))) Here is the output:
The scalar variable: IsArray(aScalar): False TypeName(aScalar): String (VarType(aScalar)=vbString): True The array variable: IsArray(anArray): True TypeName(anArray): Variant() (VarType(anArray)=vbArray+vbVariant): True IsArray(anArray(0)): False TypeName(anArray(0)): String The output shows that: For a scalar value, the "TypeName()" function returns the subtype name of the value. For a scalar value, the "VarType()" function returns the subtype code of the value. For an array value, the "TypeName()" function returns "Variant()". For an array value, the "VarType()" function returns the sum of two codes: "vbArray+vbVariant".
Try It Out
To assign a value into array element, use the name and the index number. Here is an example that assigns values into the array declared above. cars(0)="Jeep Grand Cherokee" cars(1)="Jeep Wrangler" cars(2)="Jeep Liberty" cars(3)="Jeep Cherokee Briarwood" Now we know that every element of the array has value. We can retrieve the data one at a time or all at once. For example, I can retrieve Jeep Grand Cherokee by using cars(0) or by re-assigning to it an another variable like this, car1=cars(0). We can also access to the array data using loop like this: for x=0 to 3 msgbox(cars(x)) next This simply displays all the cars on message box one at a time.
41
VBScript
Summary
There two types of arrays: fixed-size array and dynamic-size array. "Dim" and "ReDim" specify upper bound of array index, not the size. "Array" is a useful function to create a dynamic-size array quickly. "For Each" can iterate through an array with a temporary variable to hold a copy of the current element value.
Exercises
Create an array that contains 1 to 100 and print only odd numbers to the screen Create an array that contains 1 to 100 and print only even numbers to the screen
42
VBScript
Assigning an Array to a Scalar Variable. Array References. Using Array () Function. Array Error Handling.
Dim aScalar Dim anArray(1) aScalar = "Rabbit" anArray(0) = "1" anArray(1) = "2" Msgbox "anArray has type before assigning: " & TypeName(anArray) Msgbox "aScalar has type before assigning:" & TypeName(aScalar) aScalar = anArray aScalar(0) = "10" 'Array reference works like an array ReDim Preserve aScalar(2) 'The referenced array is re-sized aScalar(2) = "30" Msgbox "anArray has type after assigning:" & TypeName(anArray) Msgbox "aScalar has type after assigning:" & TypeName(aScalar)
Msgbox "aScalar(0): " & aScalar(0) Msgbox "aScalar(1): " &aScalar(1) Msgbox "aScalar(2): " & aScalar(2)
43
VBScript
Msgbox "anArray(0): " & anArray(0) Msgbox "anArray(1): " & anArray(1)
Example
Dim aReference Dim anArray(1)
aReference = anArray 'An array reference is assigned aReference(0) = "Pig" 'Accessing an element through the reference ReDim Preserve aReference(2) 'Re-sizing the referenced array aReference(2) = "Fox"
Msgbox "TypeName(aReference): " & TypeName(aReference) Msgbox "UBound(aReference): " & upperLimit For Each e In aReference Msgbox " " & e Next
Out Put:
44
VBScript
TypeName(aReference): Variant() UBound(aReference): 2 Pig Cat Fox
Arguments: Arguments element1 elementN Description The data to be assigned to the first array element. Any number of data items you wish to add to the array.
Although the array you create with the Array function is a variant array data type, the individual elements of the array can be a mixture of different data types. The initial size of the array you create is the number of arguments you place in the argument list and pass to the Array function. The lower bound of the array created by the Array function is 0. The array returned by the Array function is a dynamic rather than a static array. Once created, you can re-dimension the array using Redim, Redim Preserve, or another call to the Array function. If you don't pass any arguments to the Array function, an empty array is created. Although this may appear to be the same as declaring an array in the conventional manner with the statement Dim myArray()
Example:
Dim varArray varArray = Array(10,20,30,40,50) Dim arrTitles arrTitle = Array( Mr , Mrs , Miss , Ms )
45
VBScript
Make sure the data types match when performing comparisons. Cast one of the values to the data type of the other, and try the comparison again. Can you assign the value of a scalar variable to an array variable? The answer is simple: "No". For example: array_variable = scalar_variable If you try it, you will get a runtime error: Type mismatch. Can you assign the value of an array variable to a scalar variable? The answer is not so simple. Technically, a scalar variable is not capable to store an array. So the answer is no - you cannot assign an array directly to a scalar variable. But a scalar variable can be used to store a reference, or a pointer, of an array. So the answer is yes - you can assign an array indirectly to a scalar variable. For example: scalar_variable = array_variable The assignment operation will first create a new dynamic-size array as a copy of the specified array. The assignment operation will then create a reference of the new dynamic-size array. Finally, the reference of the new dynamic-size array is stored into the specified scalar variable. Can you assign the value of an array variable to another array variable? The answer is simple: "No". For example: another_array_variable = array_variable If you try it, you will get a runtime error: Type mismatch. Try to play with the following example below to understand how assignment operation works with scalar variables and array variables:
Example
Dim aScalar Dim anotherScalar Dim anArray(9) Dim anotherArray(9) anotherScalar = aScalar 'Creates a copy of aScalar's value anArray = aScalar aScalar = anArray 'Runtime error: Type mismatch 'Creates a copy of anArray's array
46
VBScript
Try It Out
Code: Dim aWeek(6) Msgbox "Is aWeek an array? " & IsArray(aWeek) aWeek(0) = "Sun" aWeek(4) = "Thu" aWeek(6) = "Sat" aWeek(1) = "Mon" Msgbox"Days in a week:" For i=LBound(aWeek) To UBound(aWeek) Msgbox " " & i & " = " & aWeek(i) Out Put: Is aWeek an array? True Days in a week: 0 = Sun 1 = Mon 2= 3= 4 = Thu 5= 6 = Sat
How It Works: Error 1 - Array index (subscription) must be in the range of lower bound and upper bound. Error 2 - Fixed-size array cannot be resized with "ReDim" statements.
Summary
A scalar variable can be used to hold a reference to an array. Assigning an array to a scalar variable creates a copy of the array and a reference to the copy. An array reference works like an array. "Array()" function returns a reference of a new dynamic-size array. Runtime error 'Type mismatch' happens when you try to assign scalar values or arrays to array variables.
Exercise
47
VBScript
Write a program to concatenate all of the strings in an array, each separated by a specified string separator.
48
VBScript
Session 11: Conditional Statements - "If ... Then" and "Select Case"
Learning Objectives
You will learn how to use following control statements:
Syntax:
If <condition> Then statements [Else elsestatements ] ----------------------------------------------------------------------------------------------If condition Then [statements] [ElseIf condition-n Then [ elseifstatements] ... [Else [elsestatements]] End If
Arguments:
Arguments condition statements condition-n elseifstatements Description An expression returning either True or False or an object type. One or more statements separated by colons; executed if condition is True. Same as condition. One or more statements executed if the associated condition-n is True.
49
VBScript
Elsestatements One or more statements executed if no previous condition or condition-n expression is True.
Example:
sMsg = Satisfying Condition If nAge <= 0 Or nAge > 120 Then MsgBox sMsg bFail = True End If
IfThen...Else
The IfThen structure is quite useful, but it has one limitation. Oftentimes, when people make decisions, they want to do one thing if a condition is true; otherwise, they want to do something different. Syntax:
If condition = True Then [statement1] Else [statement2] End If
Example:
If MyFavoriteRestaurantOpen = True Then Msgbox "Go To My Favorite Restaurant!" Else Msgbox "Go Home and Cook!" End If
50
VBScript Example:
If nAge = 0 Then MsgBox "Welcome to the human race!" ElseIf nAge < 0 Then MsgBox "You have to grow up a bit before you start using VBScript!" ElseIf nAge > 0 And Age < 10 Then MsgBox "If you're bold enough, you must be old enough." ElseIf nAge > 120 Then MsgBox "You're getting too old for this stuff!" Else MsgBox "You're at the perfect age to get started!" End If
Select - Case
Description: Select Case allows for conditional execution of a block of code, typically out of three or more code blocks, based on some condition. Use the Select Case statement as an alternative to complex nested If...Then...Else statements.
Syntax:
Select Case testexpression Case expressionlist-n [statements-n]] ... Case Else [elsestatements]] End Select
Arguments:
Arguments
testexpression expressionlist-n statements-n
Description
Any numeric or string expression. Required if Case appears. Delimited list of one or more expressions.
Same as condition.
51
VBScript
elseifstatements
elsestatements One or more statements executed if testexpression matches any part of expressionlist-n One or more statements executed if testexpression doesn't match any of the Case clauses
Example
varWeekDay = InputBox ("Enter the value from 1 to 7") Select Case varWeekDay Case 1: MsgBox "Sunday" Case 2: MsgBox "Monday" Case 3: MsgBox "Tuesday" Case 4: MsgBox "Wednesday" Case 5: MsgBox "Thursday" Case 6: MsgBox "Friday" Case 7: MsgBox "Saturday" End Select
Summary
"If" must be followed by a condition and the keyword "Then". "ElseIf" is one word, no space. "Case" can be followed by more than one expected values. Unlike C language, no need to use break statements in "Case" clauses.
Exercise
Write a program to print the name of the week based on user input.
52
VBScript
Using For ... Next Statements. Using While Statements Using Do ... Loop Statements
Control Structures help Make Code Repeat without increasing the length of the code.
Syntax:
For counter = start To end [Step stepcounter] [statements] [Exit For] [statements] Next
Arguments:
Arguments counter Start End Step statements Description Numeric variable used as a loop counter. The variable can't be an array element or an element of a user-defined type. Initial value of Counter. Final Value of Counter. Amount counter is changed each time through the loop. If not specified, step defaults to one. One or more statements between For and Next that are executed the specified number of times.
53
VBScript
Syntax:
For Each element In group [statements] [Exit For] [statements] Next
Arguments:
Arguments Element Group Statements Description The s ring argument is any valid string expression. If s ring contains Null, Null is returned. Name of an object collection or array. One or more statements that are executed on each item in group.
The For...Each code block is executed only if group contains at least one element. All statements are executed for each element in group in turn until either there are no more elements in group, or the loop is exited prematurely using the Exit For statement. Program execution then continues with the line of code following Next. For Each...Next loops can be nested, but each element must be unique.
Example:
For Each myObj In anObject For Each subObject In myObject sName(ctr) = subObject.Nam Property ctr = ctr + 1 Next Next
Syntax:
While condition Version [statements] Wend
Arguments:
Arguments Condition Statements Description Numeric variable used as a loop counter. The variable can't be an array element or an element of a user-defined type. One or more statements between For and Next that are executed the specified number of times.
54
VBScript
A Null condition evaluated as False. If condition evaluates to True the program code between the While and Wend statements executed. After the Wend statement is executed, control is passed back up to the While statement, where condition is evaluated again. When condition evaluates to False, program execution skips to the first statement following the Wend statement. You can nest While ...Wend loops within each other.
Example
i=3 While i <= 30 misprice = True j=2 While j <= i\2 And bIsPrime bIsPrime = i Mod j > 0 j=j+1 Wend If bIsPrime Then document.writeln("Found a prime number: " & i) End If i=i+2 Wend
Syntax:
Do [{While | Until} condition] [statements] [Exit Do] [statements] Loop Do [statements] [Exit Do] [statements] Loop [{While | Until} condition]
Arguments:
Arguments condition Description Numeric or string expression that is True or False. If condition is Null, condition is
55
VBScript
treated as False. an element of a user-defined type. statements One or more statements that are repeated while or until condition is True.
Example:
Do nCtr = nCtr + 1 ' Modify loop control variable Msg ox "Iteration " & nCtr & " of the Do loop..." & vbCrLf ' Compare to upper limit If nCtr = 10 Then Exit Do Loop Adding the until keyword after Do instructs your program to Do something until the condition is true. Its syntax is: Do Until condition code to execute Loop If condition is true before your code gets to the Do statement, the code within the Do...Loop is ignored. Adding the While keyword after Do repeats the code while a particular condition is True. When the condition becomes False, the loop is automatically exited. The syntax of the Do While statement is: Do While condition code to execute Loop Again, the code within the Do...Loop construct is ignored if condition is False then the program arrives at the loop. In some cases, you may need to execute the loop at least once. You might, for example, evaluate the values held within an array and terminate the loop if a particular value is found. In that case, you'd need to execute the loop at least once. To do this, place the until or While keyword along with the condition after the Loop statement. Do...Loop until always executes the code in the loop at least once and continues to loop until the condition is true. Likewise, do...Loop while always executes the code at least once, and continues to loop while the condition is true. A Null condition is treated as False. Your code can exit the loop at any point by executing the Exit Do statement.
Try It Out
Code: Function RandomString(len) Dim lenCount Dim tmpString Dim tmpChar Randomize 'Insure that the numbers are really random lenCount = 0 Do While lenCount < len tmpChar = Chr(Int(75 * Rnd + 48))
56
VBScript
'Random characters (letters, numbers, etc.) tmpString = tmpString & tmpChar 'Add the character to the string lenCount = lenCount + 1 'Increase the counter Loop RandomString = tmpString 'Return the string End Function Msgbox RandomString(20)
Summary
How many ways of writing a loop in VB? Answer is 7: "For ... Next". "While ... Wend". "Do While ... Loop". "Do Until ... Loop". "Do ... Loop While". "Do ... Loop Until". "For Each ... Next".
Exercises
1. Write a program to print all prime numbers from 1 to 50.
57
VBScript
Function Calls Sub Routine Calls Passing Arguments by reference & Reference Variable scope in procedure
Call Statement:
The Call statement passes program control to an explicitly named procedure or function.
Syntax:
[Call] procedurename[argumentlist]
Arguments
Parameter call argumentlist Description Required. The name of the subroutine being called. Optional. A comma-delimited list of arguments to pass to the subroutine being called.
The Call statement requires that the procedure being called be named explicitly. You cannot assign the subroutine name to a variable and provide that as an argument to the Call statement. For example, the following is an illegal use of Call:
Example:
58
VBScript
Dim sProc sProc = "PrintRoutine" Call sProc(sReport) ' Illegal: sProc is a variable
You aren't required to use the Call keyword when calling a function 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.
Function Call
Now that you've seen how to declare a function, you need to know how to call it. The benefit of using a function is that you can pass back a piece of data to the caller. The subroutine does not enable you to do this because it does not return anything. You will see a way to change variables in the calling code with a subroutine later today, but the function is a better way to get data back and forth. To call a function, you simply use the syntax
return_variable = function_name(argument1, argument2, , argumentn)
Notice that in this case, the syntax is quite a bit different from the subroutine. Here, you can assign the function to a variable, or you needn't assign it to anything. The parentheses are optional only then no arguments are passed to the function. For an example of its use, suppose you have a function called GetAge. To use the GetAge function, you could enter the statement
UserAg e= GetAge()
Notice that this function doesn't need any arguments, and the result is assigned to a variable named UserAge. The following function requires three arguments-hours, minutes, and secondsand returns the number of seconds:
Example:
Function GetSeconds(Hrs, Min, Sec) GetSeconds = Hrs * 3600 + Min * 60 + S c End Function You could then call this function using a statement like NumSeconds = GetSeconds(2, 34, 25) Where, the total number of seconds is returned to the variable NumSeconds. The statement Call GetSeconds(2, 34, 25) Would also be valid, but it wouldn't be very useful because you're not retrieving the number of seconds from the function! This simply calls a function as if it were a subroutine, without handling the return value. You can also utilize a function within an expression, such as Msgbox "There are" & GetSeconds(2,34,25) & " seconds." You don't need to assign a variable to the return of the function because the return value is automatically used within the statement. Although this is certainly legal, it is not always the best programming practice. If you want to use the result of the function more than once, you must store the result in a variable. Otherwise, you will have to call the function again and waste the
59
VBScript
computer's resources in doing the calculation all over again. Likewise, storing the value in a variable to avoid repeated calls makes the code more readable and maintainable.
aPets = Array("Bird", "Cat", "Dog", "Fish", "Rabbit") Msgbox Test 2: Reversing an array"
60
VBScript
Msgbox Before Sub: " & Join(aPets) bOk = ReverseArray(aPets) Msgbox After Sub: " & Join(aPets)
Function ReverseArray(ByRef aList) If IsArray(aList) Then iMin = LBound(aList) iMax = UBound(aList) For i=iMin to iMax\2 j = iMax - (i-iMin) vTemp = aList(i) aList(i) = aList(j) aList(j) = vTemp Next ReverseArray = True Else Msgbox Error: You are not giving an array." ReverseArray = False End If End Function
61
VBScript
Total = 50 End Sub Now the code that calls the procedure Dim Total : Total = 100 Call MySub(Total) After this code executes, the variable Total equals 50 because the code in the procedure changed its value. To pass an argument by value, use the ByVal keyword Sub MySub(ByVal Total) When you use ByVal, the procedure is passed a copy of the argument variable and not a reference to the argument variable itself. Code in the procedure cannot change the variable's value. Sub MySub(ByVal Total) Total = 50 End Sub Now the code that calls the procedure: Dim Total Total = 100 Call MySub(Total) After this code executes, Total is still equal to 100. Note that array arguments and user-defined type arguments cannot be passed ByVal. Also, using ByVal or ByRef doesn't have any effect then the argument is a literal constant--only then it's a variable. For most procedures, the default ByRef argument passing is fine. You can use ByVal then you want to ensure that code in the procedure cannot change the variable that has passed as an argument.
62
VBScript
The nice thing about rule #1 is that variables defined the main code are automatically accessible in all procedures. You don't have to pass them as reference arguments to share them in a procedure. The bad thing about rule #2 is that if you are using temporary variable in a procedure without explicit declaration, you could accidentally change the value of a global variable of the same name. Rule #3 helps us to avoid the bad impact of rule #3, if you declare all temporary variables explicitly in procedures.
Example:
Dim vGlobalDim vGlobalDim = "Cat" vGlobalNoDim = "Dog" Dim vTempDim vTempDim = "Bird" vTempNoDim = "Fish" Call ScopeCheck() Msgbox Current value after Sub:" Msgbox vGlobalDim = " & vGlobalDim Msgbox vGlobalNoDim = " & vGlobalNoDim Msgbox vLocalDim = " & vLocalDim Msgbox vLocalNoDim = " & vLocalNoDim Msgbox vTempDim = " & vTempDim Msgbox vTempNoDim = " & vTempNoDim
Sub ScopeCheck() Dim vLocalDim vLocalDim = "Apple" vLocalNoDim = "Orange" Dim vTempDim vTempDim = "Banana" vTempNoDim = "Grape" Updating values vGlobalDim = vGlobalDim & " - Updated by Sub" vGlobalNoDim = vGlobalNoDim & " - Updated by Sub" vLocalDim = vLocalDim & " - Updated by Sub" vLocalNoDim = vLocalNoDim & " - Updated by Sub" vTempDim = vTempDim & " - Updated by Sub" vTempNoDim = vTempNoDim & " - Updated by Sub"
63
VBScript
Showing values Msgbox Current value in Sub:" Msgbox vGlobalDim = " & vGlobalDim Msgbox vGlobalNoDim = " & vGlobalNoDim Msgbox vLocalDim = " & vLocalDim Msgbox vLocalNoDim = " & vLocalNoDim Msgbox vTempDim = " & vTempDim Msgbox vTempNoDim = " & vTempNoDim End Sub
Try It Out
Problem Statement: How passing arguments by reference works. Code: Msgbox Test 1: Swapping two literals by reference") Msgbox Before Sub: " & "Apple" & " | " & "Orange") Call SwapByRef("Apple", "Orange") Msgbox After Sub: " & "Apple" & " | " & "Orange") vFirst = "Dog" vSecond = "Cat" Msgbox Test 2: Swapping two variables by reference") Msgbox Before Sub: " & vFirst & " | " & vSecond) Call SwapByRef(vFirst, vSecond) Msgbox After Sub: " & vFirst & " | " & vSecond) Sub SwapByRef(ByRef vLeft, ByRef vRight) vTemp = vLeft vLeft = vRight vRight = vTemp Msgbox In Sub: " & vLeft & " | " & vRight) End Sub Out Put: Test 1: Swapping two literals by reference Before Sub: Apple | Orange In Sub: Orange | Apple After Sub: Apple | Orange Test 2: Swapping two variables by reference
64
VBScript
Before Sub: Dog | Cat In Sub: Cat | Dog After Sub: Cat | Dog
How It Works: Test 1 shows that data literal can be used for a "ByRef" argument. By you will not be able to receive the change done by the subroutine. Test 2 shows that using variable for a "ByRef" argument let us receive the change done by the subroutine. After the subroutine call, values in vFirst and vSecond have been swapped. "ByRef" keyword is optional.
Summary
A "Function" statement defines a function procedure. A "Sub" statement defines a subroutine procedure. A function procedure provides the return value through the function name. A subroutine procedure will not return any values. An "Exit Function" or "Exit Sub" statement can be used to terminate a function procedure or a subroutine procedure. A "Call" statement can be used to invoke a subroutine procedure. The keyword "Call" is optional in a "Call" statement. If keyword "Call" is omitted, the argument list can be specified without parentheses. A function procedure can be evaluated as part of an expression. A function procedure can also be evaluated with a "Call" statement. An argument is passed by reference, if it is defined with keyword "ByRef". But keyword "ByRef" is optional. So an argument is passed by reference by default. An argument is passed by value, if it is defined with keyword "ByVal". Variable defined in the main code is globally accessible in any procedure. Variable defined in a procedure is locally accessible only in that procedure. Recursive calling of a procedure is allowed.
65
VBScript
Math Functions Conversion Functions String Functions Date and Time Functions Array Functions Misc. Functions
Math Functions
Abs(vNumber) - Returns the absolute value of a specified number Atn(vNumber) - Returns the arctangent of a specified number Cos(vNumber) - Returns the cosine of a specified number (angle) Exp(vPower) - Returns e raised to a power Hex(vNumber) - Returns the hexadecimal value of a specified number Int(vNumber) - Returns the integer part of a specified number Fix(vNumber) - Returns the integer part of a specified number Log(vNumber) - Returns the natural logarithm of a specified number Oct(vNumber) - Returns the octal value of a specified number Rnd() - Returns a random number less than 1 but greater or equal to 0 Sgn(vNumber) - Returns an integer that indicates the sign of a specified number Sin(vNumber) - Returns the sine of a specified number (angle) Sqr(vNumber) - Returns the square root of a specified number Tan(vNumber) - Returns the tangent of a specified number (angle)
Conversion Functions
CBool(vVariant) - Converts an expression to a variant of subtype Boolean CByte(vVariant) - Converts an expression to a variant of subtype Byte CCur(vVariant) - Converts an expression to a variant of subtype Currency CDate(vVariant) - Converts a valid date and time expression to the variant of subtype Date CDbl(vVariant) - Converts an expression to a variant of subtype Double CInt(vVariant) - Converts an expression to a variant of subtype Integer CLng(vVariant) - Converts an expression to a variant of subtype Long CSng(vVariant) - Converts an expression to a variant of subtype Single CStr(vVariant) - Converts an expression to a variant of subtype String
66
VBScript
String Functions
InStr(sString, sSubString) - Returns the position of the first occurrence of one string within another. The search begins at the first character of the string InStrRev(sString, sSubString) - Returns the position of the first occurrence of one string within another. The search begins at the last character of the string LCase(sString) - Converts a specified string to lowercase Left(sString, iLen) - Returns a specified number of characters from the left side of a string Len(sString) - Returns the number of characters in a string LTrim(sString) - Removes spaces on the left side of a string RTrim(sString) - Removes spaces on the right side of a string Trim(sString) - Removes spaces on both the left and the right side of a string Mid(sString, iStart, iLen) - Returns a specified number of characters from a string Replace(sString, sOld, sNew) - Replaces a specified part of a string with another string a specified number of times Right(sString) - Returns a specified number of characters from the right side of a string Space(iLen) - Returns a string that consists of a specified number of spaces StrComp(sString1, sString2) - Compares two strings and returns a value that represents the result of the comparison String(iLen, sChar, iLen) - Returns a string that contains a repeating character of a specified length StrReverse(sString) - Reverses a string UCase(sString) - Converts a specified string to uppercase Asc(sString) - Converts the first letter in a string to ANSI code Chr(iInteger) - Converts the specified ANSI code to a character Date and Time Functions
CDate(vVariant) - Converts a valid date and time expression to the variant of subtype Date Date() - Returns the current system date DateAdd(sType, iInterval, tDate) - Returns a date to which a specified time interval has been added DateDiff(tDate1, tDate2) - Returns the number of intervals between two dates DatePart(sType, tDate) - Returns the specified part of a given date DateSerial(iYear, iMonth, iDate) - Returns the date for a specified year, month, and day DateValue(vVariant) - Returns a date Day(tDate) - Returns a number that represents the day of the month (between 1 and 31, inclusive) FormatDateTime(tDate, iType) - Returns an expression formatted as a date or time Hour(tDate) - Returns a number that represents the hour of the day (between 0 and 23, inclusive) IsDate(vVariant) - Returns a Boolean value that indicates if the evaluated expression can be converted to a date Minute(tDate) - Returns a number that represents the minute of the hour (between 0 and 59, inclusive)
67
VBScript
Month(tDate) - Returns a number that represents the month of the year (between 1 and 12, inclusive) MonthName(iMonth) - Returns the name of a specified month Now() - Returns the current system date and time Second(tDate0 - 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(iHour, iMinute, iSecond) - Returns the time for a specific hour, minute, and second TimeValue(tDate) Returns a time Weekday(tDate) - Returns a number that represents the day of the week (between 1 and 7, inclusive) WeekdayName(iWeekDay) - Returns the weekday name of a specified day of the week Year(tDate) - Returns a number that represents the year Array Functions
Array(vArg1, vArg2, ...) - Returns a variant containing an array IsArray(vVariant) - Returns a Boolean value that indicates whether a specified variable is an array Join(aArray) - Returns a string that consists of a number of substrings in an array LBound(aArray) - Returns the smallest subscript for the indicated dimension of an array Split(sString, sDelimiter) - Returns a zero-based, one-dimensional array that contains a specified number of substrings UBound(aArray) - Returns the largest subscript for the indicated dimension of an array
Misc. Functions
IsArray(variable) - Returns True if the specified variable is an array IsDate(variable) - Returns True if the specified variable can be converted to a date IsEmpty(variable) - Returns True if the specified variable is Empty IsNull(variable) - Returns True is the specified variable is Null IsNumeric(variable) - Returns True if the specified variable can be converted to a number IsObject(variable) - Returns True if the specified variable is an object TypeName(variable) - Returns the type name of the specified variable VarType(vVariant) - Returns the type code of the specified variable
Exercises
Print input datatype, and message false if string data. Generate a unique value, where the value should contain present system date and time. Print Number of times the letter i if displayed in the word Mississippi.
68
VBScript
69
VBScript
Out Put: False Example: IsArray Days=Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat") Msgbox IsArray(Days) Out Put: True Monday=1 Msgbox IsArray(Monday) Out Put: False Example: IsDate Date_Today="01/01/2000" Msgbox IsDate(Date_Today) Out Put: True Date_Today="01\01\2000" Msgbox IsDate(Date_Today) Out Put: False
70
VBScript
Error Handling Rules Overview IE Option Setting - Enable Script Debugging "On Error Resume Next" - Turning on Error Handling "On Error GoTo 0" - Turning off Error Handling "Err.Number" and "Err.Clear()" - Error Code and Clear Method Built-in "Err" Object Properties and Methods "Err.Raise()" - Raising Your Own Errors
71
VBScript
11. When Internet Explorer (IE) gets a runtime error with the error handling flag turned off, it will display small dialog box, if its script debug option is turned on. 12. When Windows Script Host (WSH) gets a runtime error with the error handling flag turned off, it will print out an error message.
You should get a dialog box with this message: A Runtime Error has occurred. Do you wish to Debug? Line: 8 Error: Division by zero
You can click the "No" button to close the dialog box.
72
VBScript
What happened in the example: When IE tries to execute the "x = 1/0" statement, a runtime error "Division by zero" is raised. IE stops executing the rest of the VBScript code, because the error handling flag is turned off by default. IE displays a dialog box asking your confirmation to start the debugging tool. "Err" object properties are printed on the dialog box, telling us the type of error, and where it occurs.
73
Summary
Runtime errors will be managed by the host environment, if you don't manage them. "On Error Resume Next" turns on the error handling flag, which causes the host environment to continue executing the next statement after raising a runtime error. "On Error GoTo 0" turns off the error handling flag, which causes the host environment to stop executing the current procedure after raising a runtime error. The "Err" object is built-in object representing the last runtime error. "Err.Number > 0" can be used to see if a runtime error has occurred or not. "Err.Clear()" method can be used to clear the "Err" object. "Err.Raise()" method can be used to raise your own runtime errors.
74
VBScript
"RegExp" Class and Object for Regular Expression Support "MatchCollection" and "SubMatches" Collection Objects "Set oRegExp = New RegExp" - Creating RegExp Objects Example of Regular Expression Match and Replacement
75
76
VBScript
' Repeat matches on the entire string oRegExp.Global = True ' Ignore cases while matching the pattern oRegExp.IgnoreCase = True Now the "RegExp" object, oRegExp, is ready to be used to match again any given string following operations: ' Returns True if the pattern matched at least once. bFound = oRegExp.Test(string) ' Returns a copy of the given string with each match replaced. sCopy = oRegExp.Replace(string, replacement) ' Returns a MatchCollection object containing matches. Set oMatches = oRegExp.Execute(string) Code: Example: .Pattern txt="Automation is fast" Set objReg=CreateObject("vbscript.regexp") objReg.Pattern="i" Msgbox objReg.Replace(txt,"##") Out Put: Automat##on is fast
Summary
Regular expression describes one or more strings to match when you search a body of text. The expression serves as a template for matching a character pattern to the string that is being searched. A regular expression consists of ordinary characters (for example, letters a through z) and special characters, as known metacharacters.
Exercise
Write Regular expression verifying email address1.
77
VBScript
References
Websites www.w3schools.com http://www.tizag.com/vbscriptTutorial/
Books
78