vbscript handout
TRANSCRIPT
Handout:VBScript Version: VBScript/Handout/xxxx/0.1
Date: 28-09-10
Cognizant
500 Glen Pointe Center West
Teaneck, NJ 07666
Ph: 201-801-0233
www.cognizant.com
VBScript
2
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
3
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
4
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
If…Then...Else ............................................................................................................................50
Deciding Between Several Alternatives .....................................................................................50
Select - Case ..............................................................................................................................51
Summary ....................................................................................................................................52
Excerise ....................................................................................... Error! Bookmark not defined.
VBScript
5
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
6
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
7
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.
Pre-requisite
Associate should have basic programming knowledge.
VBScript
8
Session 1: Introduction of VBScript - Visual Basic Scripting Edition
Learning Objectives
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
9
Using VBScript with Internet Explorer
Internet Explorer (IE) is a Microsoft application that can be used a Web browser to view Web pages. IE also supports a VBScript host environment that allows you to embed VBScript codes into source codes of Web pages - HTML documents.
VBScript codes embedded in HTML documents will be executed while IE is rendering HTML documents on the browser window. This is also called client side scripting, because script codes are executed on the client machine instead of the server machine.
To add VBScript codes into your HTML documents, you need to use the "script" tag with the "language=vbscript" attribute. Inside the "script" tag, you can place any number of VB statements. Here is the syntax of adding VBScript codes in HTML documents:
... (HTML tags)
<script language=vbscript>
... (VB statements)
</script>
... (HTML tags)
Now let's try to write our first VBScript code in a HTML document.
1. Open the Notepad to enter the following HTML document:
<html>
<body>
<script language="vbscript">
Msgbox("Hello world! - VBScript in IE")
</script>
</body>
</html>
2. Save the HTML document as hello_vb.html.
3. View the HTML document with IE. You should see the following message in the IE window:
Hello world! - VBScript in IE
Congratulations. You have successfully written a VBScript code for the host environment supported in IE!
What happened here was:
We have added a "script" tag in our HTML document, hello_vb.html.
We included a simple VBScript code inside the "script" tag.
The VBScript code calls the "Msgbox" function, which is a function provided by the IE host environment to insert a text string into the HTML document.
We ran IE to view hello_vb.html and got exactly what we expected.
Using VBScript with Internet Information Services
Internet Information Services (IIS) is a Microsoft product that offers and manages the Internet services, like the Web (HTTP) server, and the email (SMTP) server.
IIS also supports a VBScript host environment that allows you to embed VBScript codes into source codes of Web pages - HTML documents. VBScript codes embedded in HTML documents will be executed while IIS is fetching HTML documents on the Web server to deliver to the client machine. This is also called server side scripting, because script codes are executed on the server machine instead of the client machine.
VBScript
10
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.
Using VBScript with Windows Script Host
Windows Script Host (WSH) is a Windows administration tool that provides host environments for several scripting languages including VBScript.
VBScript codes included in script files will be executed by WSH directly on the Windows operating system.
If you are running a Windows XP system, you can try these steps to run a simple VBScript code with Windows Script Host:
1. Create a script file called hello.vbs:
WScript.StdOut.WriteLine "Hello World! - VBScript in WSH"
2. Run hello.vbs with the "cscript" command in a command window:
C:\herong>cscript hello.vbs
Microsoft (R) Windows Script Host Version 5.6
Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.
VBScript
11
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.
Using Visual Basic with Microsoft Access
As a comparison, this tutorial shows you how to write Visual Basic code and run it as a macro with Microsoft Access.
Microsoft Access is a Microsoft application that can be used to store and manage data in database tables. Microsoft Access also supports a macro module that allows you to write macro code with Visual Basic (VB) language.
If you have Microsoft Access installed on your Windows system, you can follow the steps below to create a simple application in Visual Basic language within Microsoft Access.
1. Run Microsoft Access, and create a blank Access Database called vb_tutorial.mdb.
2. Click Insert > Module from the menu. The Microsoft Visual Basic window shows up.
3. Enter the following code into the empty code module:
Sub Main()
MsgBox ("Hello world! - Visual Basic in Access")
End Sub
4. Click File > Save from the menu. Enter "Hello" as the module name and save it.
5. Click Run > Run Sub/UserForm from the menu. The macro selection dialog box shows up.
6. Select "Main" macro, and click "Run". A dialog box shows up with the following message:
Hello world! - Visual Basic in Access
Congratulations. You have successfully written a Visual Basic macro in Microsoft Access!
What happened here was:
We have added a VB macro called "Hello" to our Access database, vb_tutorial.mdb.
We have added a VB procedure called "Main" in the VB macro. Access calls this procedure as a macro.
The "Main" procedure calls the "Msgbox" function, which is a VB built-in function that displays Windows dialog box with the specified text message.
We ran the "Main" procedure and got exactly what we expected.
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.
VBScript
12
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.
VBScript
13
Session 2: Variant Data Type, Subtypes, and Literals
Learning Objectives
Data Type and Subtypes
Data Literals
Data Literal Examples
String Data Literals
Date and Time Data Literals
"Variant" - Data Type and Subtypes
Interestingly, VBScript has only one data type called "Variant", which can be used store different kinds of data depending on how it is used. This tells us that VBScript is a loosely typed, or dynamically typed, language.
Even every piece of data in VBScript is considered as the same data type, "Variant", it can be grouped into a specific category of data based on its value. These categories of data are called subtypes.
VBScript supports the following 13 data subtypes:
Byte: Using 1 byte to express integers ranging from 0 to 255.
Integer: Using 2 bytes to express signed integers ranging from -32,768 to 32,767.
Long: Using 4 bytes to express signed integers ranging from -2,147,483,648 to 2,147,483,647.
Single: Using 4 bytes to express real numbers in floating-point format ranging from -3.402823e38 to -1.401298e-45 for negative values, and from 1.401298e-45 to 3.402823e38 for positive value.
Double: Using 8 bytes to express real numbers in floating-point format ranging from -1.79769313486232e308 to -4.94065645841247e-324 for negative values, and from 4.94065645841247e-324 to 1.79769313486232e308 for positive values.
Currency: Using 8 bytes to express real numbers in decimal format ranging from -922,337,293,685,477.5808 to 922,337,293,685,477.5807.
String: Using 1 byte per character to express a sequence of characters up to approximately 2 billion characters.
Boolean: Using 2 bytes to express two Boolean values: True and False.
Date: Using 8 bytes to express dates ranging from January 1, 100 to December 31, 9999.
Empty: A special subtype to represent a variable that has not been assigned with any value yet.
Null: A special subtype to represent a variable assigned with a null value.
Object: A special subtype to represent a reference to an object.
Error: A special subtype to represent an error number.
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:
VBScript
14
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 (#), #31-Dec-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.
Data Literal Examples
Now let's write a simple VBScript code
Msgbox("7=" & (7) & " : " & TypeName(7))
Msgbox("CByte(7)=" & (CByte(7)) & " : " _
& TypeName(CByte(7)))
Msgbox("777=" & (777) & " : " & TypeName(777))
Msgbox("777777=" & (777777) & " : " & TypeName(777777))
Msgbox("9.99=" & (9.99) & " : " & TypeName(9.99))
Msgbox("CSng(9.99)=" & (CSng(9.99)) & " : " _
& TypeName(CSng(9.99)))
Msgbox("0.00314159e30=" & (0.00314159e30) & " : " _
& TypeName(0.00314159e30))
Msgbox("333.333e200=" & (333.333e200) & " : " _
& TypeName(333.333e200))
Msgbox("CCur(9.99)=" & (CCur(9.99)) & " : " _
& TypeName(CCur(9.99)))
Msgbox("""Hello""=" & ("Hello") & " : " _
& TypeName("Hello"))
Msgbox("TRUE=" & (TRUE) & " : " & TypeName(TRUE))
Msgbox("#31-Dec-1999#=" & (#31-Dec-1999#) & " : " _
& TypeName(#31-Dec-1999#))
Msgbox("Empty=" & (Empty) & " : " & TypeName(Empty))
Msgbox("Null=" & (Null) & " : " & TypeName(Null))
Several notes about this VBScript example:
VBScript
15
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
String Data Literals
In the previous section, we learned that a String data literal is a sequence of characters enclosed
in double quotes ("), like "Hello".
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 ("").
VBScript
16
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 (').
Date and Time Data Literals
In the previous section, we learned that a date literal is a string representing a date and/or time
enclosed in hash signs (#).
Here are some details about how to write a date and/or time literal:
You can write a date literal with the date part only, like #31-Dec-1999#.
You can write a date literal with the time part only, like #21:26:00#.
You can write a date literal with both date and time parts, like #31-Dec-1999 21:26:00#.
You can also write a date literal with the ISO format, like #1999-12-31 21:26:00#.
You can also write a date literal with the US format, like #12/31/1999 9:26:00 PM#.
You can NOT write a date literal with milliseconds, like #31-Dec-1999 21:26:00.123#.
Here is a tutorial example on how to write date and time in different formats:
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#))
Here is the output of the sample script:
#31-Dec-1999# = 12/31/1999
VBScript
17
#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
VBScript
18
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 (#).
Test your Understanding
Please try out the following example
Msgbox(DateAdd("yyyy",1,"31-Jan-10") ) Msgbox(DateAdd("q",1,"31-Jan-10")) Msgbox(DateAdd("m",1,"31-Jan-10")) Msgbox(DateAdd("y",1,"31-Jan-10")) Msgbox(DateAdd("d",1,"31-Jan-10")) Msgbox(DateAdd("w",1,"31-Jan-10") ) Msgbox(DateAdd("ww",1,"31-Jan-10") ) Msgbox(DateAdd("h",1,"31-Jan-10 08:50:00")) Msgbox(DateAdd("n",1,"31-Jan-10 08:50:00")) Msgbox(DateAdd("s",1,"31-Jan-10 08:50:00"))
Exercises
Write the program to print today‟s date and current time
VBScript
19
Session 3: Arithmetic Operations
Learning Objectives
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
VBScript
20
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.
VBScript
21
Modulo Arithmetic (Mod)
The Mod function is another powerful arithmetic operator. Essentially, the Mod function returns the remainder after dividing one number into another. The syntax for the function is
Result = a Mod b
Consider what happens when you divide 2 into 5. The value 2 divides evenly into 5 twice with a
remainder of 1. If you've ever performed long division, the expression would look like this:
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)
VBScript
22
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.
Test your Understanding
What is output for the below snippet
2 * 3 + 6 / 2
Exercises
What is output for below program?
2147483648 mod 2
Session 4: Numeric Comparison Operations and Logical Operations Learning Objectives
Numeric Comparisons
Logical Operations
VBScript
23
Numeric comparisons
Numeric comparisons are operations that:
Operates on two numeric operands.
Produces a Boolean value by applying the comparison operation specified by the operator.
There are 6 numeric comparison operations supported in VB:
Equal to (=): Resulting (True) if two operands are numerically equal.
Not equal to (<>): Resulting (True) if two operands are numerically not equal.
Greater than (>): Resulting (True) if the first operand is numerically greater than the second operand.
Less than (<): Resulting (True) if the first operand is numerically less than the second operand.
Greater than or equal to (>=): Resulting (True) if the first operand is numerically greater than or equal to the second operand.
Less than or equal to (<=): Resulting (True) if the first operand is numerically less than or equal to the second operand.
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)
How It Works:
Here is the output:
True
False
False
VBScript
24
True
True
False
Summary
VB supports 6 numeric comparisons.
VB supports 4 logical operations
Test your Understanding
What is the output for below snippet?
Msgbox(True And True)
Msgbox(True Or True)
Msgbox(Not True)
Msgbox(True Xor True)
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)){
Session 5: String Operations - Concatenation and Comparison
Learning Objectives
Concatenation
String Comparison Operations
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.
VBScript
25
See the next section for example on how concatenation works.
String Comparison Operations
String comparison operations are operations that:
Operates on two string operands.
Produces a Boolean value by applying the comparison operation specified by the operator.
There are 6 string comparison operations supported in VB:
Equal to (=): Resulting (True) if two strings have the same length and the same characters at the same positions.
Not equal to (<>): Resulting (True) if two strings are not equal.
Greater than (>): Resulting (True) if the first string is greater than the second string. The logic of (>) operation works by comparing every character in the first string with the character at the same position in the second string from left to right. If there is no character left in the second string, stop operation and return (True); Or if the character in the first string has a higher ASCII value, stop operation and return (True); Or if two characters are identical, continue to the next character; Otherwise, stop operation and return (False).
Less than (<): Resulting (True) if two strings are not equal, and the first string is not greater than the second string.
Greater than or equal to (>=): Resulting (True) if the first string is greater than the second string or two strings are equal.
Less than or equal to (<=): Resulting (True) if the first string is less than the second string or two strings are equal.
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
VBScript
26
Summary
Use (&) operator to concatenate strings.
String comparisons are based character ASCII values.
Exercises
What is output for the below program?
Msgbox("ABC" <> "abc")
Session 6: Variable Declaration and Assignment Statement
Learning Objectives
Variable Declaration
Assigning Values to Variables
Variable Default Values
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
VBScript
27
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.
Assigning Values to Variables - "=" Statement
Values are assigned to variables creating an expression as follows:
the variable is on the left side of the expression and the value you want to assign to the variable is on the right. For example:
B=200
Empty - The Default Value of a Variable
What is the default, or initial, value of a variable after the declaration and before the first assignment? The answer is: Empty.
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
VBScript
28
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
VBScript
29
Session 7: Expression and Order of Operation Precedence
Learning Objectives
What Is an Expression?
Precedence of Operations
Expression Example
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
VBScript
30
Try It Out
Msgbox("")
Msgbox(777)
Msgbox(0.00314159e30)
Msgbox(TRUE)
„Expressions with a single operation
Msgbox("")
Msgbox(3.333e200 + 0.111e200)
Msgbox(11.0 * 1.0e20)
Msgbox(1 = 1)
Msgbox(9.9999e-1 < 1)
Msgbox(True Or False)
' Expressions with multiple operations
Msgbox("")
Msgbox(+ 1 - 2 * 3 / 4)
Msgbox(+ 1 - 2 * 3 / 4 = ( + 1 - 2 ) * 3 / 4)
Msgbox(1 - 2 * 3 / 4 = (1 - 2) * 3 / 4 And 0.9999 < 1)
How It Works:
Here is the output:
777
3.14159E+27
True
3.444E+200
1.1E+21
True
True
True
-0.5
False
False
Summary
Expression always results a single value.
VBScript
31
Test your Understanding
What is the result of the following code fragment?
Msgbox("1 + 2 = " + 1 + 2)
Msgbox("1 + 2 = " + (1 + 2))
Answer: 1 + 2 = 12 and 1 + 2 = 3, respectively. If either (or both) of the operands of the + operator is a string, the other is automatically cast to a string. String concatenation and addition have the same precedence. Since they are left-associative, the operators are evaluated left-to-right. The parenthesis in the second statement ensures that the second + operator perform addition instead of string concatenation.
Exercises
Explain the order of operation precedence for the below snippet
year % 4 == 0 && year % 100 != 0 || year % 400 == 0
VBScript
32
Session 8: Statement Syntax and Statement Types
Learning Objectives
What Is a Statement?
Types of Statements
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.
VBScript
33
Summary
Statements can be continued on the next line with (_) character.
VB source code is case insensitive.
VBScript
34
Session 9: Array Data Type and Related Statements
Learning Objectives
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.
"Dim x()" - Declaring Array Variables
VBScript supports a number of ways to declare array variables:
1. Explicit Declaration with Fixed Size - Using "Dim" statement with size included as:
Dim variable_name(upper_bound) [As data_type]
where "upper_bound" is positive integer specifying the upper bound of the element index, and "data_type" is a data type keyword. Array declared in this way has a fixed size (number of elements). By default, the size of an array is the upper bound plus 1, because index starts from 0. This size cannot be changed. If "As data_type" is not specified, default data type "Variant" will be used.
2. Explicit Declaration with Dynamic Size - Using "Dim" and "ReDim" statements as shown in the following syntax:
Dim variable_name() [As data_type]
...
ReDim [Preserve] variable_name(upper_bound)
VBScript
35
...
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.
"x(i)" - Accessing Array Elements with Indexes
Retrieving values from array elements can be done through their indexes like this:
... = ... array_variable(index) ...
VB also offers a special loop statement, "For Each" statement, to retrieve every element in an array like this:
For Each element_variable In array_variable
... = ... element_variable ...
Next
This statement will iterate through every element in the specified array. At each iteration, The value of the current element will be copied to the specified temporary variable, "element_variable". The order of iteration is based on element index values from the lower bound to the upper bound.
"Dim x(n)" - Fixed-Size Array Example
To show you how fixed size array works, see the following example, array_fixed_size.
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))
VBScript
36
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.
"Dim x()" - Dynamic-Size Array Example
To show you how dynamic-size array works, see the following example, array_dynamic_size.
Dim aYear()
Msgbox("Check 1: Is aYear an array? " & IsArray(aYear))
' aYear(0) = "Jan" 'Error 1: Subscription out of range
' iSize = UBound(aYear)+1 'Error 2: Index out of range
ReDim aYear(5)
Msgbox("Check 2: Is aYear an array? " & IsArray(aYear))
aYear(0) = "Jan"
aYear(1) = "Feb"
aYear(5) = "Jun"
ReDim Preserve aYear(11)
aYear(10) = "Nov"
Msgbox ("Months in a year:")
For i=LBound(aYear) To UBound(aYear)
Msgbox(" " & i & " = " & aYear(i))
Next
Here is the output:
VBScript
37
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.
"For Each" Statement Example
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 )
VBScript
38
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.
"Erase" Statement - Removing All Elements in an Array
It is interesting to know that VB offers a special statement called "Erase" to remove all values in an
array:
Erase array_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:")
VBScript
39
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)
Here is the output:
Favorite pets:
Dog
Cat
Favorite fruits:
Apple
Orange
Erasing arrays...
Pets left:
Count = 2
Fruits left:
Count = 0
VBScript
40
Data Type "Variant()" - Array of Variant Values
Earlier, we learned that VBScript supports only one data type: Variant, The above statement needs
to be revised now because of arrays.
VBScript supports only one data type, Variant, for scalar values. Array is another data type
supported in VBScript for non-scalar values.
A non-scalar value is a complex value that contains an internal structure to store more than a
single piece of data.
An array is non-scalar value that contains an array structure to store a list of scalar values.
Since there is only one data type, Variant, for scalar values, VBScript only supports one array type:
Array of Variant, or Variant()
Applying data type rules to variables, now we know:
A variable can be declared as a scalar variable using "Dim x".
A variable can be declared as an array variable using "Dim y()".
A scalar variable can be used to store a scalar value of data type, Variant.
An array variable can be used to store an array of scalar values of data type, Variant.
A scalar variable has a data type of Variant.
An array variable has a data type of Variant() - Array of Variant.
To show you the difference between a scalar variable and an array variable, see the following
example
Dim aScalar
Dim anArray(1)
aScalar = "Rabbit"
anArray(0) = "Dog"
anArray(1) = "Cat"
Msgbox("")
Msgbox("The scalar variable:")
Msgbox(" IsArray(aScalar): " & IsArray(aScalar))
Msgbox(" TypeName(aScalar): " & TypeName(aScalar))
Msgbox (" (VarType(aScalar)=vbString): " _
& (VarType(aScalar)=vbString))
Msgbox("")
Msgbox("The array variable:")
Msgbox(" IsArray(anArray): " & IsArray(anArray))
Msgbox(" TypeName(anArray): " & TypeName(anArray))
Msgbox(" (VarType(anArray)=vbArray+vbVariant): " _
& (VarType(anArray)=vbArray+vbVariant))
Msgbox(" IsArray(anArray(0)): " & IsArray(anArray(0)))
Msgbox(" TypeName(anArray(0)): " _
VBScript
41
& 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.
VBScript
42
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.
Test your Understanding
Dim x(2), y(2)
x(0) =1
x(1)=2
x(2)=3
x = y
Msgbox(y)
What is output for above snippet?
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
VBScript
43
Session 10: Array References and Array Assignment Statements Learning Objectives
Assigning an Array to a Scalar Variable.
Array References.
Using Array () Function.
Array Error Handling.
Assigning an Array to a Scalar Variable
A variable containing a single value is a scalar variable. 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.
Dim aScalar, anArray(1)
aScalar = anArray
Assigning an array to a scalar variable is valid. It will be used to store a reference of an array. A
new dynamic-size array will be created as a copy of the array represented by array variable,
anArray.
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)
VBScript
44
Msgbox "anArray(0): " & anArray(0)
Msgbox "anArray(1): " & anArray(1)
Array References Work Like Arrays
An array reference is a scalar value. This is why it can be assigned to a scalar variable. A scalar
variable holding an array reference can be used like an array variable.
In Below Example:
array_reference(i)" represents the element of index i of the referenced array.
"ReDim Preserve array_reference(n)" resets the size of the referenced array.
When an array reference is used as a function argument, the referenced array is passed
into the function, not the reference. For example, "TypeName(array_reference)" returns
Variant().
Example
Dim aReference
Dim anArray(1)
anArray(0) = "Dog"
anArray(1) = "Cat"
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"
upperLimit = UBound(aReference) 'The referenced array is passed
Msgbox "TypeName(aReference): " & TypeName(aReference)
Msgbox "UBound(aReference): " & upperLimit
For Each e In aReference
Msgbox " " & e
Next
Out Put:
VBScript
45
TypeName(aReference): Variant()
UBound(aReference): 2
Pig
Cat
Fox
Using Array () Function
The Array function returns a variant array containing the elements whose values are passed to the
function as arguments.
Syntax:
Array(element1, element2, elementN,....)
Arguments:
Arguments Description
element1 The data to be assigned to the first array element.
elementN 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 )
Array Error Handling
One common error that we face while working with Array is Type Miss Match:
You attempted to compare values of incompatible data types for example, comparing a string and
a numeric value.
To correct this error
VBScript
46
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 'Runtime error: Type mismatch
aScalar = anArray 'Creates a copy of anArray's array
anotherArray = anArray 'Runtime error: Type mismatch
VBScript
47
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
VBScript
48
Write a program to concatenate all of the strings in an array, each separated by a specified string separator.
VBScript
49
Session 11: Conditional Statements - "If ... Then" and "Select Case"
Learning Objectives
You will learn how to use following control statements:
If... Then... Else
Select Case
If… Then Control Structure
If… then… control helps in decision making. It executes a statement or block of statements based
on the Boolean (True or false) value of an expression.
Syntax:
If <condition> Then statements [Else elsestatements ]
----------------------------------------------------------------------------------------------- If condition Then
[statements] [ElseIf condition-n Then
[ elseifstatements] ... [Else
[elsestatements]] End If
Arguments:
Arguments Description
condition An expression returning either True or False or an object type.
statements One or more statements separated by colons; executed if condition is True.
condition-n Same as condition.
elseifstatements One or more statements executed if the associated condition-n is True.
VBScript
50
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
If…Then...Else
The If…Then 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
Deciding Between Several Alternatives
A variation on the If...Then...Else statement allows you to choose from several alternatives. Adding
ElseIf clauses expands the functionality of the If...Then...Else statement so you can control
program flow based on different possibilities.
Syntax:
If condition1 = True Then
[statement1]
ElseIf condition2 = True Then
[statement2]
ElseIf condition3 = True Then
[statement3]
End If
VBScript
51
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 Description
testexpression Any numeric or string expression.
expressionlist-n Required if Case appears. Delimited list of one or more expressions.
statements-n Same as condition.
VBScript
52
elseifstatements One or more statements executed if testexpression matches any part of
expressionlist-n
elsestatements
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.
VBScript
53
Session 12: Loop Statements
Learning Objectives
Using For ... Next Statements.
Using While Statements
Using Do ... Loop Statements
Control Structures help Make Code Repeat without increasing the length of the code.
For ... Next Statements
Description:
For… Next defines a loop that executes a given number of times, as determined by a loop counter. To use the For... Next loop, you must assign a numeric value to a counter variable. This counter is either incremented or decremented automatically with each iteration of the loop. In the For statement, you specify the value that is to be assigned to the counter initially and the maximum value the counter will reach for the block of code to be executed. The Next statement marks the end of the block of code that is to execute repeatedly, and also serves as a kind of flag that indicates the counter variable is to be modified.
Syntax:
For counter = start To end [Step stepcounter]
[statements] [Exit For]
[statements] Next
Arguments:
Arguments Description
counter Numeric variable used as a loop counter. The variable can't be an array element or an element of a user-defined type.
Start Initial value of Counter.
End Final Value of Counter.
Step Amount counter is changed each time through the loop. If not specified, step defaults to one.
statements
One or more statements between For and Next that are executed the specified number of times.
For Each…. Next
Description:
For Each… Next repeats a group of statements for each element in an array or an object
collection.
VBScript
54
Syntax:
For Each element In group
[statements] [Exit For]
[statements] Next
Arguments:
Arguments Description
Element The s ring argument is any valid string expression. If s ring contains Null, Null is returned.
Group Name of an object collection or array.
Statements 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
While . . . Wend Statement
Description: The While …Wend statement executes a series of statements as long as a given condition is true.
Syntax:
While condition Version [statements] Wend
Arguments:
Arguments Description
Condition Numeric variable used as a loop counter. The variable can't be an array element or an element of a user-defined type.
Statements One or more statements between For and Next that are executed the specified number of times.
VBScript
55
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
Do… Loop Statement
Description Repeatedly executes a block of code while or until a condition becomes true.
Syntax:
Do [{While | Until} condition]
[statements] [Exit Do]
[statements] Loop Do
[statements] [Exit Do]
[statements] Loop [{While | Until} condition]
Arguments:
Arguments Description
condition Numeric or string expression that is True or False. If condition is Null, condition is
VBScript
56
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))
VBScript
57
'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.
VBScript
58
Session 13: Functions and Sub Procedure Learning Objectives
Function Calls
Sub Routine Calls
Passing Arguments by reference & Reference
Variable scope in procedure
What is a Procedure?
Description:
A unit of code defined outside of the main execution code. A procedure will not be executed unless
it is invoked by the main execution code or another procedure.
A procedure is a grouping of code statements that can be called by an associated name to
accomplish a specific task or purpose in a program. Once a procedure is defined, it can be called
from different locations in the program as needed.
A Sub procedure is a series of VBScript statements (enclosed by Sub and End Sub statements)
that perform actions but don't return a value. A Sub procedure can take arguments (constants,
variables, or expressions that are passed by a calling procedure). If a Sub procedure has no
arguments, its Sub statement must include an empty set of parentheses ().
Call Statement: The Call statement passes program control to an explicitly named procedure or function.
Syntax:
[Call] procedurename[argumentlist]
Arguments
Parameter Description
call Required. The name of the subroutine being called.
argumentlist 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:
VBScript
59
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 seconds-and 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
VBScript
60
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.
Sub Routine Call
Now that you've learned how to create a subroutine, how do you call one? You can call a
subroutine throughout the rest of the application once you've declared and created it. You can call
subroutines by using the Call keyword or just entering the name of the subroutine on a line of
code. For example, to call a subroutine called ShowMessage, you could enter
ShowMessage "This is the message."
You could also use the Call key ord and enter
Call ShowMessage("This is the message.")
Notice that in the first method, you do not place parentheses around the arguments of the
subroutine. On the other hand, if you use Call, you must enclose the arguments in parentheses.
This is simply a convention that VBScript requires.
What if a subroutine has no arguments? To call the subroutine ShowAboutMessage, you could
enter
ShowAboutMessage
Or
Call ShowAboutMessage()
Or you could use
Call ShowAboutMessage
The first method simply lists the name of the subroutine. The second method uses Call but doesn't require parentheses because the subroutine has no arguments. Whether you use the parentheses when you call or declare a subroutine with no arguments is a personal preference about writing code. When you call a subroutine without the Call statement, it can be more difficult to figure out the difference between a subroutine and a variable in your code, especially if your code is lengthy. Although the choice is up to you, it is generally recommended that you always use the Call statement when calling subroutines for the sake of readability.
Passing Arrays as Arguments
Arrays can also be passed as arguments. If an array is passed by reference, the procedure is working on the same array as the calling code. If an array is passed by value, the procedure is working on an independent copy of the original array in the calling code.
Example:
Msgbox “Test 1: Reversing a data literal"
bOk = ReverseArray("Apple")
aPets = Array("Bird", "Cat", "Dog", "Fish", "Rabbit")
Msgbox “Test 2: Reversing an array"
VBScript
61
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
Passing Arguments into Procedures
Procedures are an essential part of almost every program. When you define a procedure, whether it's a Function or a Sub procedure, you need to decide whether the procedure arguments are passed by reference or by value.
What difference does it make?
VBScript default is to pass arguments by reference. You can include the ByRef keyword in an
argument list if desired but, because this is the default, it has no effect:
Sub Foo(ByRef Arg1, ByRef Arg2)
The procedure is passed the address of the argument variable (in other words, a reference to the
variable):
Dim Total
Call MySub(Total)
In this example, MySub receives a reference to Total. The practical consequence of this is that
code in MySub can change Total. Here's an example. First, the procedure:
Sub MySub(Total)
VBScript
62
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.
Variable Scope in Procedure
Variable Scope is the area of source code where a variable is accessible.
If you are not using procedures, variable scope is very simple. The scope of a variable is: from the
statement where it is defined to the last statement of the code.
If you are using procedures, variable scope gets more complex. Here are some basic rules:
1. Global - If a variable is defined in the main code, its scope is from the statement where it is
defined to the last statement of the entire code including all procedures.
2. Local - If a variable is defined in a procedure code, its scope is from the statement where it is
defined to the last statement of the procedure.
3. Collision - If a variable is explicitly defined in a procedure code has the same name as a variable
defined in the main code, the variable of the main code become in-accessible within this
procedure.
There are some interesting consequences of those rules:
VBScript
63
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"
VBScript
64
„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
VBScript
65
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.
VBScript
66
Session 14: Built In Functions
Learning Objectives
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
VBScript
67
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)
VBScript
68
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”.
VBScript
69
Session15: Inspecting Variables Received in Procedures
Learning Objectives
This Session provides tutorial examples and notes on inspecting variables received in procedures.
Topics include why variables received must be inspected before using them, guidelines on how to
inspect variables, crash-free code example to convert anything into a Long integer.
Variable Inspection - Data Type Validation
Variable Inspection - Data Type Validation
If are writing a procedure, and receiving a variable from the calling code through an argument, you cannot always assume that value of the variable is of certain subtype. If you code your procedure with some assumptions, your code will crash if the calling code fails to meet those assumptions.
To better protect your code, you want to inspect the value first, and write your code based on the result of the inspection. Variable inspection can be performed at 3 different levels:
1. Determine the structure type of the variable. Is it an object, array, or scalar.
2. Determine the data subtype of the variable. If it is an object, check its properties; If it is an array, check its elements; If it is a scalar, check the subtype of the value: Byte, Integer, Long, Single, Double, Date, Currency, Boolean, or String.
3. Determine the status of the data. Is it Empty or Null.
VBScript offers a number of built-in functions to help you to inspect a variable:
IsObject(variable) - Returns True if the specified variable is an object
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
TypeName(variable) - Returns the type name of the specified variable
SubType(variable) - Returns the subtype code of the specified variable
Code:
Example: IsObject
Set x=Nothing
Msgbox IsObject(x)
Out Put: True
y="apple"
Msgbox IsObject(y)
VBScript
70
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
VBScript
71
Session 16: Error Handling Flag and the "Err" Object
Learning Objectives
This Session provides brief information on runtime error handling. Topics include the default error
handling behaviour; 'On Error Resume Next' and 'On Error GoTo 0' statements; catching errors
with (Err.Number > 0); clear Err object with Err.Clear(); raise your own errors with Err.Raise(...).
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
Error Handling Rules Overview
VBScript offers some limited facilities to help your manage runtime errors. Here is a summary of rules that will help you to properly manage runtime errors in your VBScript code:
1. The "On Error Resume Next" statement can be used to turn on the error handling flag.
2. The "On Error GoTo 0" statement can be used to turn off the error handling flag.
3. User defined procedures have their own error handling flags. This means that each user defined procedure should be having its own "On Error Resume Next" or "On Error GoTo 0" statement to turn on or off its own error handling flag.
4. By default, error handling flags of all user defined procedures and the main code are turned off.
5. By default, the host environment provides a built-in object called "Err" to hold runtime error information.
6. When a runtime error occurs, the host environment will set values to properties of the "Err" object and raise a runtime error.
7. When a runtime error is raised and the current error handling flag is on, the host environment will continue to execute the next statement.
8. With the error handling flag turned on, you can inspect "Err" object properties to determine how to handle the error and continue your code execution.
9. When a runtime error is raised in a procedure and the current error handling flag is off, the host environment will stop executing the procedure, transfer execution control to the calling code, and raise the same runtime error in the calling code.
10. When a runtime error is raised in the main code and the current error handling flag is off, the host environment will stop executing the main code, and take some additional steps.
VBScript
72
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.
IE Option Setting - Enable Script Debugging
Since we have been using Internet Explorer (IE) as the host environment in previous sections, let's look at what will IE do when the VBScript raises a runtime error.
IE 6.0 supports an option called "Disable Script Debugging (Internet Explorer)" on the "Advanced" tab. Let's uncheck it, meaning enable script debugging as shown in the picture below:
Now run the following VBScript example:
Example:
Dim x
X = 1/0
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.
VBScript
73
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.
"On Error Resume Next" - Turning on Error Handling
We have seen what happens when the error handling flag is turned off in the previous section. Now let's see how the "On Error Resume Next" statement should be used:
By default, the error handling flag is turned off.
You can turn on the error handling flag at time your want by entering the "On Error Resume Next" statement.
Once the error handling flag is turned on, execution will not be stopped when a runtime error occurs.
You can use the condition of (Err.Number>0) to determine a runtime error has occurred or not.
If a runtime error has occurred, use Err object properties to get more information about the error:
Err.Number - "Err" object property containing the error code.
Err.Description - "Err" object property containing the error description.
Err.Source - "Err" object property containing error source identification.
"On Error GoTo 0" - Turning off Error Handling
If you want to catch the first runtime error is a large section of code, you need to:
Enter the "On Error Resume Next" statement in the main code to turn on the error handling flag for the main code.
Put that section of code into a new subroutine procedure.
Enter the "On Error Goto 0" statement in the new procedure to turn off the error handling flag for that procedure.
Check the Err.Number property right after calling that procedure
"Err.Number" and "Err.Clear ()" - Error Code and Clear Method
VBScript
74
Built-in "Err" Object Properties and Methods
1. "Err" is a built-in object representing the last runtime error that occurred during the execution.
2. "Err" has the following important properties.
Err.Number - The code value of the runtime error. For example, Err.Number = 11 is the code value of the "Division by zero" error. See the list of common error code values below.
Err.Description - The description string of the runtime error.
Err.Source - The source string of the runtime error.
3. "Err" has the following important methods.
Err.Raise (number, source, description) - Raises a new runtime error with your own error code, source and description.
Err.Clear () - Clears the current runtime error.
"Err.Raise()" - Raising Your Own Errors
VBScript also allows you to use the "Err" to raise your own runtime error with the Err.Raise() method:
Call Err.Raise(number, source, description)
Where:
"number" is an integer in the range of 0 and 65535 to represent a specific error condition. But lower values are already used by VBScript for predefined errors. So you should use higher values, like 60000, 60000, ...
"source" is a string to identify where the error occurred.
"description" is a string to describe the error condition.
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.
VBScript
75
Session 17: Regular Expression Pattern Match and Replacement
Learning Objectives
This Session provides tutorial examples and notes on regular expression support in VBScript.
Topics include 'RegExp' class and objects, setting up regular expressions and match option flags,
applying a pattern for matches and replacements, checking MatchCollection and SubMatches
collection objects, example of regular expression pattern match and replacement.
"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
"RegExp" Class and Object for Regular Expression Support
VBScript supports a built-in class called "RegExp" to provide regular expression support.
In order to perform a regular expression task, you need to create a RegExp object with this syntax:
Set oRegExp = New RegExp
Then we are ready to use properties and methods supported on the RegExp object, oRegExp:
oRegRex.Pattern - A String property containing the regular expression string to represent the search pattern.
oRegRex.Global - A Boolean property representing the global search flag. If turned on, the search will be applied multiple times on the entire string.
oRegRex.IgnoreCase - A Boolean property representing the ignore-case search flag. If turned on, the search will be applied case insensitively.
oRegRex.Test (string) - A method returning True, if a pattern match is found in the given string.
oRegRex.Execute (string) - A method returning a MatchCollection collection object that contains a list of Match objects. Each Match object represents a pattern match found in the given string.
oRegRex.Replace (string, replacement) - A method returning a copy of the given string with each pattern match found and replaced with the replacement string.
The Match object has the following properties:
oMatch.Length - An integer property representing the number of characters of this pattern match.
oMatch.FirstIndex - An integer property representing the position where this pattern match was found in the string.
oMatch.Value - An String property representing this match found in the string. The "Value" property is the default property. So the "Value" property will be returned if a Match object is used in a String context.
oMatch.SubMatches - A SubMatches collection property that contains a list of Strings. Each string represents a sub pattern match.
VBScript
76
"MatchCollection" and "SubMatches" Collection Objects
We are mentioned that MatchCollection and SubMatches objects are collection objects. All collection objects share same properties and methods:
oCollection.Count - An integer property representing the number of items in this collection.
oCollection.Item(i) - A method returning the item at position i in this collection. The "Item(i)" method is defined as the default method of a collection object. So you can call this method without the method name. For example, oCollection(0) is equivalent to oCollection.Item(0), referring to the first item in this collection.
A collection object can also be used like an array in a "For Each" statement:
For Each e In oCollection ... = ... e ... ' e Represents the current item End For
If you apply the above properties and methods to a MatchCollection object, oMatches, returned from the oRegExp.Execute(string) method, you should understand the following interesting examples:
oMatches.Count - Number of Match objects.
oMatches.Item(0) - The first Match object.
oMatches(0) - The first Match object.
oMatches(1).SubMatches - The SubMatches collection object of the second Match object.
oMatches(1).SubMatches.Count - The number of sub match strings of the second Match object.
oMatches(1).SubMatches.Item(1) - The second sub match string of the second Match object.
oMatches(1).SubMatches(1) - The second sub match string of the second Match object.
"Set oRegExp = New RegExp" - Creating RegExp Objects
1. Create an empty RegExp object with a "Set" statement and set it to a variable:
Dim oRegExp Set oRegExp = New RegExp
Where "RegExp" is the name of the "RegExp" class; "New" is an operator to create a new object out of a class; "oRegExp" is Variant variable holding the new "RegExp" object.
2. Assign a regular expression string as the match pattern following regular expression rules. Here are some examples of regular expressions - see a regular expression manual for more examples:
' A pattern to match any word ending with "ee". ' No sub matches defined. oRegExp.Pattern = "\w+ee\s" ' A pattern to match any email address. ' 3 sub matches defined in the pattern. oRegExp.Pattern = "(\w+)@(\w+)\.(\w+)"
3. Set match flags, "Global" and "IgnoreCase". For examples:
VBScript
77
' 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.
VBScript
78
References
Websites
www.w3schools.com
http://www.tizag.com/vbscriptTutorial/
Books