Version: VBScript/Handout/xxxx/0.1 Version: VBScript/Handout/xxxx/0.1 Date: 28-09-10 Date: 28-09-10 Cognizant Cognizant 500 Glen Pointe Center West 500 Glen Pointe Center West Teaneck, NJ 07666 Teaneck, NJ 07666 Ph: 201-801-0233 Ph: 201-801-0233 www.cognizant.com www.cognizant.com
TABLE OF CONTENTS
TABLE OF CONTENTS
Introduction
Introduction ... 7... 7 About
About this this Module ...Module ... ... 77 Target
Target Audience Audience ... ... 77 Module
Module Objectives ...Objectives ... ... 77 Pre-requisite
Pre-requisite ... 7... 7 Session 1: Int
Session 1: Introduction of roduction of VBScript - VBScript - Visual Basic ScrVisual Basic Scripting Edition ... ipting Edition ... 88 Learning
Learning Objectives ...Objectives ... ... 88 What
What Is Is VBScript?...VBScript?... ... 88 Using
Using VBScript with VBScript with Internet Internet Explorer ... Explorer ... 99 Using
Using VBScript with VBScript with Internet Internet Information Information Services Services ... ... 99 Using VBScript
Using VBScript with Windows with Windows Script Host Script Host ...10...10 Using Visual
Using Visual Basic with Basic with Microsoft Access ...Microsoft Access ...11...11 Summary
Summary ...11....11 Session 2: Variant Data Type, Subtypes, and Literals ...13 Session 2: Variant Data Type, Subtypes, and Literals ...13
Learning
Learning Objectives ...Objectives ...13....13 "Variant" -
"Variant" - Data TData Type and ype and Subtypes Subtypes ...13...13 Data
Data Literals ...Literals ...13...13 Data Literal
Data Literal Examples ...Examples ...14...14 String
String Data Data Literals ...Literals ...15...15 Date and
Date and Time Time Data Literals ...Data Literals ...16...16 Try
Try It It Out ...Out ...17...17 Summary
Summary ...18....18 Test
Test your Understanding ...your Understanding ...18....18 Exercises
Exercises ...18....18 Session
Session 3: 3: Arithmetic OpArithmetic Operations erations ...19...19 Learning
Learning Objectives ...Objectives ...19....19 Arithmetic Arithmetic (+) ...(+) ...19...19 Subtraction Subtraction (-) ...(-) ...19...19 Multiplication Multiplication (*) ...(*) ...20...20 Division
Division (/ (/ and and \) \) ...20...20 Exponents
Exponents (^) ...(^) ...20...20 Modulo Arithmetic
Modulo Arithmetic (Mod) ...(Mod) ...21....21 Exponentiation
Exponentiation Operator ...Operator ...21...21 Try
TABLE OF CONTENTS
TABLE OF CONTENTS
Introduction
Introduction ... 7... 7 About
About this this Module ...Module ... ... 77 Target
Target Audience Audience ... ... 77 Module
Module Objectives ...Objectives ... ... 77 Pre-requisite
Pre-requisite ... 7... 7 Session 1: Int
Session 1: Introduction of roduction of VBScript - VBScript - Visual Basic ScrVisual Basic Scripting Edition ... ipting Edition ... 88 Learning
Learning Objectives ...Objectives ... ... 88 What
What Is Is VBScript?...VBScript?... ... 88 Using
Using VBScript with VBScript with Internet Internet Explorer ... Explorer ... 99 Using
Using VBScript with VBScript with Internet Internet Information Information Services Services ... ... 99 Using VBScript
Using VBScript with Windows with Windows Script Host Script Host ...10...10 Using Visual
Using Visual Basic with Basic with Microsoft Access ...Microsoft Access ...11...11 Summary
Summary ...11....11 Session 2: Variant Data Type, Subtypes, and Literals ...13 Session 2: Variant Data Type, Subtypes, and Literals ...13
Learning
Learning Objectives ...Objectives ...13....13 "Variant" -
"Variant" - Data TData Type and ype and Subtypes Subtypes ...13...13 Data
Data Literals ...Literals ...13...13 Data Literal
Data Literal Examples ...Examples ...14...14 String
String Data Data Literals ...Literals ...15...15 Date and
Date and Time Time Data Literals ...Data Literals ...16...16 Try
Try It It Out ...Out ...17...17 Summary
Summary ...18....18 Test
Test your Understanding ...your Understanding ...18....18 Exercises
Exercises ...18....18 Session
Session 3: 3: Arithmetic OpArithmetic Operations erations ...19...19 Learning
Learning Objectives ...Objectives ...19....19 Arithmetic Arithmetic (+) ...(+) ...19...19 Subtraction Subtraction (-) ...(-) ...19...19 Multiplication Multiplication (*) ...(*) ...20...20 Division
Division (/ (/ and and \) \) ...20...20 Exponents
Exponents (^) ...(^) ...20...20 Modulo Arithmetic
Modulo Arithmetic (Mod) ...(Mod) ...21....21 Exponentiation
Exponentiation Operator ...Operator ...21...21 Try
Summary
Summary ...22....22 Test
Test your Understanding ...your Understanding ...22....22 Exercises
Exercises ...22....22 Session 4: Num
Session 4: Numeric Comparison eric Comparison Operations and Operations and Logical Operations Logical Operations ...22...22 Learning
Learning Objectives ...Objectives ...22....22 Numeric
Numeric comparisons ...comparisons ...23....23 Logical
Logical Operations ...Operations ...23....23 Try
Try It It Out ...Out ...23...23 Summary
Summary ...24....24 Test
Test your Understanding ...your Understanding ...24....24 Exercises
Exercises ...24....24 Session 5: String
Session 5: String Operations - Operations - Concatenation and Comparison ...24Concatenation and Comparison ...24 Learning
Learning Objectives ...Objectives ...24....24 Concatenation
Concatenation ...24...24 String Comparison
String Comparison Operations ...Operations ...25...25 Try
Try It It Out ...Out ...25...25 Summary
Summary ...26....26 Exercises
Exercises ...26....26 Session 6: Variable
Session 6: Variable Declaration and Declaration and Assignment Statement ...Assignment Statement ...26...26 Learning
Learning Objectives ...Objectives ...26....26
Variable Declaration and "Dim"
Variable Declaration and "Dim" StatementStatement...26...26 Assigning Values to Variables - "="
Assigning Values to Variables - "=" Statement...Statement...27....27 Empty - The
Empty - The Default Value of Default Value of a Variable ..a Variable ...27...27 Try
Try It It Out ...Out ...27...27 Summary
Summary ...28....28 Exercises
Exercises ...28....28 Session 7: Expression
Session 7: Expression and Order of Operand Order of Operation Precedence .ation Precedence ...29...29 Learning
Learning Objectives ...Objectives ...29....29 What
What Is Is an an Expression? Expression? ...29...29 Try
Try It It Out ...Out ...30...30 Summary
Summary ...30....30 Test
Test your Understanding ...your Understanding ...31....31 Exercises
Exercises ...31....31 Session 8:
Session 8: Statement Syntax Statement Syntax and Statement and Statement Types Types ...32...32 Learning
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… ThenControl Structure ...49
If…Then...Else...50
Deciding Between Several Alternatives ...50
Select - Case ...51
Summary ...52 Excerise ...Error! Bookmark not defined.
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
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
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
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
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.
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
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 langua ge 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 f rom 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.
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.
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 floatingpoint 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 floatingpoint 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:
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) & " : " & T ypeName(TRUE)) Msgbox("#31-Dec-1999#=" & (#31-Dec-1999#) & " : " _
& TypeName(#31-Dec-1999#))
Msgbox("Empty=" & (Empty) & " : " & TypeName(Empty)) Msgbox("Null=" & (Null) & " : " & TypeName(Null))
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 charactersenclosed 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 ("").
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
#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
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
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
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 commandResult = 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
byb
and puts the result into the variablec
. Similarly, you could use numbers and perform a division such asc = a / 2
This, in this case, divides the variable a in half. If the variable
a
were set to some valid numeric value, say3
, the result stored inc
would be1.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 variablec
.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.
Modulo Arithmetic (Mod)
The
Mod
function is another powerful arithmetic operator. Essentially, theMod
function returns the remainder after dividing one number into another. The syntax for the function isResult = a Mod b
Consider what happens when you divide
2
into5
. The value2
divides evenly into5
twice with a remainder of1
. If you've ever performed long division, the expression would look like this:As you can see, the remainder is indeed
1
. TheMod
operator returns the remainder. In the expressionResult = 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(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
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: TrueFalse False
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.
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
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
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 = Truev = "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
Session 7: Expression and Order of Operation
Precedence
Learning Objectives
What Is an Expression? Precedence of Operations Expression ExampleWhat 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
Try It Out
Msgbox("") Msgbox(777)
Msgbox(0.00314159e30) Msgbox(TRUE)
„Expressionswith 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
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
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.
Summary
Statements can be continued on the next line with (_) character. VB source code is case insensitive.
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] ...
...
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))
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
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
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 ("")
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
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)): " _
& 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
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
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:" & T ypeName(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:" & T ypeName(aScalar)
Msgbox "aScalar(0): " & aScalar(0) Msgbox "aScalar(1): " &aScalar(1) Msgbox "aScalar(2): " & aScalar(2)
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
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.
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
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.