VBScript Handout
November 14, 2016 | Author: aruns2012 | Category: N/A
Short Description
Download VBScript Handout...
Description
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
TABLE OF CONTENTS Introduction .......................................................... ............................................................................................................................. ......................................................................... ......7 About this Module ......................................................................................................................... .........................................................................................................................7 Target Audience ............................................................ ........................................................................................................................... ...............................................................7 Module Objectives ........................................................................................................................ ........................................................................................................................7 Pre-requisite ........................................................ ........................................................................................................................... ......................................................................... ...... 7 Session 1: Introduction Int roduction of VBScript - Visual Basic Scripting Scr ipting Edition ......................................8 Learning Objectives ...................................................................................................................... ......................................................................................................................8 What Is VBScript?................................................ VBScript?................................................................................................................... ......................................................................... ......8 Using VBScript with Internet Explorer ..........................................................................................9 Using VBScript with Internet Information Services .............................................................. ....................................................................... .........9 Using VBScript with Windows Script Host ................................................................... ..................................................................................10 ...............10 Using Visual Basic with Microsoft Access ..................................................................................11 ..................................................................................11 Summary ............................................................. ................................................................................................................................ .......................................................................11 ....11 Session 2: Variant Data Type, Subtypes, and Literals .............................................................13 Learning Objectives ................................................................................................................ ....................................................................................................................13 ....13 "Variant" - Data Type T ype and Subtypes ............................................................... ...........................................................................................13 ............................13 Data Literals .......................................................................................... ................................................................................................................................13 ......................................13 Data Literal Examples ................................................................................................................14 ................................................................................................................14 String Data Literals .....................................................................................................................15 .....................................................................................................................15 Date and Time Data Literals ........................................................................... .......................................................................................................16 ............................16 Try It Out .......................................................................... .....................................................................................................................................17 ...........................................................17 Summary ............................................................. ................................................................................................................................ .......................................................................18 ....18 Test your Understanding ............................................................................................................18 ............................................................................................................18 Exercises ............................................................. ................................................................................................................................ .......................................................................18 ....18 Session 3: Arithmetic Operations Op erations ........................................................ ...............................................................................................19 .......................................19 Learning Objectives ................................................................................................................ ....................................................................................................................19 ....19 Arithmetic (+) ..............................................................................................................................19 ..............................................................................................................................19 Subtraction (-) .............................................................................................................................19 .............................................................................................................................19 Multiplication (*) ..........................................................................................................................20 ..........................................................................................................................20 Division (/ and \) ............................................................. ..........................................................................................................................20 .............................................................20 Exponents (^) ............................................................................................................... ..............................................................................................................................20 ...............20 Modulo Arithmetic (Mod) ............................................................................................................21 ............................................................................................................21 Exponentiation Operator ............................................................................................ .............................................................................................................21 .................21 Try It Out .......................................................................... .....................................................................................................................................21 ...........................................................21
2
VBScript
TABLE OF CONTENTS Introduction .......................................................... ............................................................................................................................. ......................................................................... ......7 About this Module ......................................................................................................................... .........................................................................................................................7 Target Audience ............................................................ ........................................................................................................................... ...............................................................7 Module Objectives ........................................................................................................................ ........................................................................................................................7 Pre-requisite ........................................................ ........................................................................................................................... ......................................................................... ...... 7 Session 1: Introduction Int roduction of VBScript - Visual Basic Scripting Scr ipting Edition ......................................8 Learning Objectives ...................................................................................................................... ......................................................................................................................8 What Is VBScript?................................................ VBScript?................................................................................................................... ......................................................................... ......8 Using VBScript with Internet Explorer ..........................................................................................9 Using VBScript with Internet Information Services .............................................................. ....................................................................... .........9 Using VBScript with Windows Script Host ................................................................... ..................................................................................10 ...............10 Using Visual Basic with Microsoft Access ..................................................................................11 ..................................................................................11 Summary ............................................................. ................................................................................................................................ .......................................................................11 ....11 Session 2: Variant Data Type, Subtypes, and Literals .............................................................13 Learning Objectives ................................................................................................................ ....................................................................................................................13 ....13 "Variant" - Data Type T ype and Subtypes ............................................................... ...........................................................................................13 ............................13 Data Literals .......................................................................................... ................................................................................................................................13 ......................................13 Data Literal Examples ................................................................................................................14 ................................................................................................................14 String Data Literals .....................................................................................................................15 .....................................................................................................................15 Date and Time Data Literals ........................................................................... .......................................................................................................16 ............................16 Try It Out .......................................................................... .....................................................................................................................................17 ...........................................................17 Summary ............................................................. ................................................................................................................................ .......................................................................18 ....18 Test your Understanding ............................................................................................................18 ............................................................................................................18 Exercises ............................................................. ................................................................................................................................ .......................................................................18 ....18 Session 3: Arithmetic Operations Op erations ........................................................ ...............................................................................................19 .......................................19 Learning Objectives ................................................................................................................ ....................................................................................................................19 ....19 Arithmetic (+) ..............................................................................................................................19 ..............................................................................................................................19 Subtraction (-) .............................................................................................................................19 .............................................................................................................................19 Multiplication (*) ..........................................................................................................................20 ..........................................................................................................................20 Division (/ and \) ............................................................. ..........................................................................................................................20 .............................................................20 Exponents (^) ............................................................................................................... ..............................................................................................................................20 ...............20 Modulo Arithmetic (Mod) ............................................................................................................21 ............................................................................................................21 Exponentiation Operator ............................................................................................ .............................................................................................................21 .................21 Try It Out .......................................................................... .....................................................................................................................................21 ...........................................................21
2
VBScript Summary ............................................................. ................................................................................................................................ .......................................................................22 ....22 Test your Understanding ............................................................................................................22 ............................................................................................................22 Exercises ............................................................. ................................................................................................................................ .......................................................................22 ....22 Session 4: Numeric Num eric Comparison Operations and Logical Operations ...................................22 Learning Objectives ................................................................................................................ ....................................................................................................................22 ....22 Numeric comparisons ............................................................................................................. .................................................................................................................23 ....23 Logical Operations .................................................................................................................. ......................................................................................................................23 ....23 Try It Out .......................................................................... .....................................................................................................................................23 ...........................................................23 Summary ............................................................. ................................................................................................................................ .......................................................................24 ....24 Test your Understanding ............................................................................................................24 ............................................................................................................24 Exercises ............................................................. ................................................................................................................................ .......................................................................24 ....24 Session 5: String Operations - Concatenation and Comparison ............................................24 Learning Objectives ................................................................................................................ ....................................................................................................................24 ....24 Concatenation.................................................................. .............................................................................................................................24 ...........................................................24 String Comparison Operations ...................................................................................................25 ...................................................................................................25 Try It Out .......................................................................... .....................................................................................................................................25 ...........................................................25 Summary ............................................................. ................................................................................................................................ .......................................................................26 ....26 Exercises ............................................................. ................................................................................................................................ .......................................................................26 ....26 Session 6: Variable Declaration and Assignment Statement ..................................................26 ..................................................26 Learning Objectives ................................................................................................................ ....................................................................................................................26 ....26 Variable Declaration and "Dim" Statement ................................................................................26
Assigning Values to Variables - "=" Statement....................................................................... Statement...........................................................................27 ....27 Empty - The Default Value of a Variable ..................................................................... ....................................................................................27 ...............27 Try It Out .......................................................................... .....................................................................................................................................27 ...........................................................27 Summary ............................................................. ................................................................................................................................ .......................................................................28 ....28 Exercises ............................................................. ................................................................................................................................ .......................................................................28 ....28 Session 7: Expression and Order of Operation Oper ation Precedence ...................................................29 ...................................................29 Learning Objectives ................................................................................................................ ....................................................................................................................29 ....29 What Is an Expression? ............................................................. ..............................................................................................................29 .................................................29 Try It Out .......................................................................... .....................................................................................................................................30 ...........................................................30 Summary ............................................................. ................................................................................................................................ .......................................................................30 ....30 Test your Understanding ............................................................................................................31 ............................................................................................................31 Exercises ............................................................. ................................................................................................................................ .......................................................................31 ....31 Session 8: Statement Syntax and Statement Types ............................................................ .................................................................32 .....32 Learning Objectives ................................................................................................................ ....................................................................................................................32 ....32
3
VBScript What Is a Statement? .................................................................................................................32 Types of Statements ...................................................................................................................32 Summary ....................................................................................................................................33 Summary .....................................................................................Error! Bookmark not defined. Session 9: Array Data Type and Related Statements ...............................................................34 Learning Objectives ....................................................................................................................34 What Is an Array? .......................................................................................................................34 "Dim x()" - Declaring Array Variables .........................................................................................34 "x(i)" - Accessing Array Elements with Indexes ..........................................................................35 "Dim x(n)" - Fixed-Size Array Example .......................................................................................35 "Dim x()" - Dynamic-Size Array Example ...................................................................................36 "For Each" Statement Example ..................................................................................................37 "Erase" Statement - Removing All Elements in an Array ...........................................................38 Data Type "Variant()" - Array of Variant Values .........................................................................40 Try It Out .....................................................................................................................................41 Summary ....................................................................................................................................42 Test your Understanding ............................................................................................................42 What is output for above snippet? ..............................................................................................42 Exercises ....................................................................................................................................42 Session 10: Array References and Array Assignment Statements ........................................43 Learning Objectives ....................................................................................................................43 Assigning an Array to a Scalar Variable .....................................................................................43 Array References Work Like Arrays ...........................................................................................44 Using Array () Function ...............................................................................................................45 Array Error Handling ...................................................................................................................45 Try It Out .....................................................................................................................................47 Summary ....................................................................................................................................47 Exercise ......................................................................................................................................47 Session 11: Conditional Statements - "If ... Then" and "Select Case" ...................................49 Learning Objectives ....................................................................................................................49 If… Then Control Structure .........................................................................................................49 If…Then...Else ............................................................................................................................50
Deciding Between Several Alternatives .....................................................................................50 Select - Case ..............................................................................................................................51 Summary ....................................................................................................................................52 Excerise .......................................................................................Error! Bookmark not defined.
4
VBScript Session 12: Loop Statements .....................................................................................................53 Learning Objectives ....................................................................................................................53 For ... Next Statements ...............................................................................................................53 For Each…. Next ........................................................................................................................53
While . . . Wend Statement .........................................................................................................54 Do… Loop Statement .................................................................................................................55
Try It Out .....................................................................................................................................56 Summary ....................................................................................................................................57 Exercises ....................................................................................................................................57 Session 13: Functions and Sub Procedure ...............................................................................58 Learning Objectives ....................................................................................................................58 What is a Procedure? .................................................................................................................58 Function Call ...............................................................................................................................59 Sub Routine Call .........................................................................................................................60 Passing Arrays as Arguments ....................................................................................................60 Passing Arguments into Procedures ..........................................................................................61 Variable Scope in Procedure ......................................................................................................62 Try It Out .....................................................................................................................................64 Summary ....................................................................................................................................65 Session 14: Built In Functions ....................................................................................................66 Learning Objectives ....................................................................................................................66 Math Functions ...........................................................................................................................66 Conversion Functions .................................................................................................................66 String Functions ..........................................................................................................................67 Date and Time Functions ...........................................................................................................67 Array Functions...........................................................................................................................68 Misc. Functions ...........................................................................................................................68 Exercises ....................................................................................................................................68 Session15: Inspecting Variables Received in Procedures .....................................................69 Learning Objectives ....................................................................................................................69 Variable Inspection - Data Type Validation ................................................................................69 Session 16: Error Handling Flag and the "Err" Object .............................................................71 Learning Objectives ....................................................................................................................71 Error Handling Rules Overview ..................................................................................................71 IE Option Setting - Enable Script Debugging .............................................................................72
5
VBScript You should get a dialog box with this message: ........................................................................72 "On Error Resume Next" - Turning on Error Handling ................................................................73 "On Error GoTo 0" - Turning off Error Handling .........................................................................73 "Err.Number" and "Err.Clear ()" - Error Code and Clear Method ...............................................73 Built-in "Err" Object Properties and Methods .............................................................................74 "Err.Raise()" - Raising Your Own Errors.....................................................................................74 Summary ....................................................................................................................................74 Session 17: Regular Expression Pattern Match and Replacement .........................................75 Learning Objectives ....................................................................................................................75 "RegExp" Class and Object for Regular Expression Support ....................................................75 "MatchCollection" and "SubMatches" Collection Objects...........................................................76 "Set oRegExp = New RegExp" - Creating RegExp Objects .......................................................76 Exercise .......................................................................................Error! Bookmark not defined. Summary ....................................................................................................................................77 References ....................................................................................................................................78 Websites .....................................................................................................................................78 Books ..........................................................................................................................................78
6
VBScript
Introduction About this Module This module covers the implementation, use and generation of the VBScript.
Target Audience This module is beneficial for the programmer and automation script developers of the functional automation tools like HP Quick Test Progression, IBM Rational Robot which support VBScript.
Module Objectives This module will impart the knowledge of the VBScript. After completion of this module user will be able use VBScript to its core extent. User will be able to work with VBScript data types, built in functions, write user defined functions, procedures, conditional statements, conditional loops etc.
Pre-requisite Associate should have basic programming knowledge.
7
VBScript
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
8
VBScript
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) ... (VB statements) ... (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: Msgbox("Hello world! - VBScript in IE") 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.
9
VBScript One way to add VBScript codes into your HTML documents for IIS to execute is to use the ASP (Active Server Pages) technology. If you have IIS installed on your Windows system, you can use the following steps to run a simple VBScript code in IIS. 1. Go to Control Panel, then Administrative Tools, then Internet Services Manager, and right mouse click on Default Web Site, then select properties command. 2. Click on Home Directory tab on the properties dialog box, and then click the Configuration button. 3. Click on App Mappings tab on the configuration dialog box, then check to see the following line in the mapping area to make sure that ASP is supported by IIS: Extension Executable Path Verbs .asp
c:\winnt\system32\inetsrv\asp.dll GET,HEAD,POST,TRACE
4. Create the following hello.asp file: 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.
10
VBScript
Hello World! - VBScript in WSH Congratulations. You have successfully written a VBScript code for the host environment provided by WSH! What happened here was: We created a simple VBScript code file. The VBScript code calls the "WScript.StdOut.WriteLine" function, which is a function provided by the WSH host environment to print a text string to the standard output channel - the command window in this case.
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.
11
VBScript WSH (Windows Script Host) provides a VBScript host environment th at allows you to run stand alone script code files. If you are interested to learn Visual Basic, you can write Visual Basic codes in Microsoft Access and run them as macros.
12
VBScript
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:
13
VBScript Byte Literal - Not exist. So there is no way to enter a Byte value into a VBScript code. If you need a Byte value, you can use the conversion function CByte() to convert an integer number value into a Byte value, like CByte(7). Integer Literal - A singed integer number within the Integer value range in decimal format, like -8, 0, and 777. Long Literal - A singed integer number within the Long value range, but outside the Integer value range, in decimal format, like -888888 and 777777. Single Literal - Not exist. So there is no way to enter a Single value into a VBScript code. If you need a Single value, you can use the conversion function CSng() to convert a real number value into a Single value, like CSng(0.00314159e30). Double: Literal - A signed real number within the Double value range in the scientific format with a decimal point and/or an exponential part, like 9.99, 0.00314159e30 and 333.333e200. Currency Literal - Not exist. So there is no way to enter a Currency value into a VBScript code. If you need a Currency value, you can use the conversion function CCur() to convert a decimal number value into a Currency value, like CCur(9.99). String Literal - A sequence of characters enclosed in double quotes ("), like "Hello". Boolean Literal - One of two keywords: True and False. Date Literal - A string representing a date and/or time enclosed in hash signs (#), #31Dec-1999#. Empty Literal - The keyword: Empty Null Literal - The keyword: Null Object Literal - Not sure. We will find out later. Error Literal - Not sure. We will find out later.
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)) Several notes about this VBScript example:
14
VBScript String concatenation operation, "&", is used to join strings together. A special function, TypeName(), is used to show the subtype of the specified value. The statement continuation character (_) is used to join multiple lines into a single statement. Output: 7=7 : Integer CByte(7)=7 : Byte 777=777 : Integer 777777=777777 : Long 9.99=9.99 : Double CSng(9.99)=9.99 : Single 0.00314159e30=3.14159E+27 : Double 333.333e200=3.33333E+202 : Double CCur(9.99)=9.99 : Currency "Hello"=Hello : String TRUE=True : Boolean #31-Dec-1999#=12/31/1999 : Date Empty= : Empty Null= : Null The output conforms our understanding of data literal rules described in the previous section: "7=7 : Integer" shows that small integer numbers are not recognized as Byte values. "CByte(7)=7 : Byte" shows that CByte() returns a Byte value. "777777=777777 : Long" shows that large integer numbers are recognized as Long values. "9.99=9.99 : Double" shows that small real numbers are not recognized as Single values. "CSng(9.99)=9.99 : Single" shows that CSng() returns a Single value. "0.00314159e30=3.14159E+27 : Double" shows that real numbers are normalized into the standard floating-point format. "CCur(9.99)=9.99 : Currency" shows that CCur() returns a Currency value. "TRUE=True : Boolean" shows that keywords are not case sensitive. Key word "TRUE" is the same as "True". "#31-Dec-1999#=12/31/1999 : Date" shows that more than one date formats are supported. Both dd-MMM-yyyy and mm/dd/yyyy are valid. "Empty= : Empty" shows that the Empty value is converted into a blank string in a string concatenation operation. "Null= : Null" shows that the Null value is converted into a blank string in a string concatenation operation
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 ("").
15
VBScript
Msgbox("Ding...") Msgbox("He said: ""Hello?""") Msgbox("She said: ""Hello, whose calling?""") Here is the output of the sample script: Ding... He said: "Hello?" She said: "Hello, whose calling?" By the way, VBScript does not support string literals with single quotes (').
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
16
VBScript #21:26:00# = 9:26:00 PM #31-Dec-1999 21:26:00# = 12/31/1999 9:26:00 PM ISO format: #1999-12-31 21:26:00# = 12/31/1999 9:26:00 PM US format: #12/31/1999 9:26:00 PM# = 12/31/1999 9:26:00 PM Notice that the host environment is using the US format as the default format.
Try It Out Code: Msgbox("#31-Dec-1999# = " & (#31-Dec-1999#)) Msgbox("#21:26:00# = " & (#21:26:00#)) ' Msgbox("#21:26:00.123# = " & (#21:26:00.123#)) Msgbox("#31-Dec-1999 21:26:00# = " _ & (#31-Dec-1999 21:26:00#)) Msgbox() Msgbox("ISO format:") Msgbox("#1999-12-31 21:26:00# = " _ & (#1999-12-31 21:26:00#)) Msgbox() Msgbox("US format:") Msgbox("#12/31/1999 9:26:00 PM# = " _ & (#12/31/1999 9:26:00 PM#))
How It Works: #31-Dec-1999# = 12/31/1999 #21:26:00# = 9:26:00 PM #31-Dec-1999 21:26:00# = 12/31/1999 9:26:00 PM ISO format: #1999-12-31 21:26:00# = 12/31/1999 9:26:00 PM US format: #12/31/1999 9:26:00 PM# = 12/31/1999 9:26:00 PM
17
VBScript
Summary 13 subtypes of Variant supported in VBScript. Data literals can be entered in VBScript statement for different subtypes in different formats. String literals must be enclosed in double quotes ("). ("") represents (") in string literals. Date literals must be enclosed in slash signs (#).
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
18
VBScript
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
19
VBScript You can combine addition and subtraction in the same code statement: Result = May + June - July
Multiplication (*) Addition and subtraction are important, but you also need to be able to multiply values together. In most computer languages, the * symbol is used to indicate multiplication, not the x symbol. You might be able to use x on paper, but to the computer, x is a variable, not a multiplication symbol. If you enter the command Result = 3 x 2 The interpreter will give you a syntax error. Rather, you should enter the command Result = 3 * 2 to be correct.
Division (/ and \) The division operator is the last of the four commonly used arithmetic operators. Among the common arithmetic operators, division is the most complicated arithmetic operation a computer performs. This shouldn't surprise you if you remember learning long division in grade school math class. VBScript has two types of division operators. The first operator handles numbers with decimal points. Usually referred to as the floating-point division operator, it's represented by the / symbol in code listings. c=a/b This code divides the variable a by b and puts the result into the variable c. Similarly, you could use numbers and perform a division such as c=a/2 This, in this case, divides the variable a in half. If the variable a were set to some valid numeric value, say 3, the result stored in c would be 1.5. Integer division is performed the same way floating-point division is, but the operator is different. Rather than use a forward slash ( / ), you use a backward slash ( \ ). The following code shows the syntax: Result = a \ b Returning to the t-shirt example, if you coded the bonus calculation in your script as c = 1204 / 16 You would end up with the value of 75.25 stored in variable c.
Exponents (^) The exponent operator calculates a result based on the following formula: Result = number ^ exponent The expression Result = 2 ^ 3 Evaluates to 8 because 2 * 2 * 2 = 8. The exponent function, which is available on most scientific and business calculators, is often used in formulas relating to science, engineering, and accounting.
20
VBScript
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 expression
1. The Mod operator returns the remainder. In the
Result = 5 Mod 2 The return variable Result is equal to 1.
Exponentiation Operator Exponentiation is the ability to raise a number to the power of another number. This operation is expressed using the ^ operator (Shift + 6). In Microsoft Visual Basic (and Microsoft Access), this formula is written as: y^x and means the same thing. Either or both y and x can be values or expression, but they must carry valid values that can be evaluated. When the operation is performed, the value of y is raised to the power of x. You can display the result of such an operation in a field using the assignment operator as follows: =y^x You can also assign the operation to an expression as follows: Total = y^x
Try It Out Msgbox(3.333e200 + 0.111e200)
21
VBScript Msgbox(1.0e0 - 1.0e20) Msgbox(11.0 * 1.0e20) Msgbox(20.0e20 / 3.0e0) Msgbox(3 ^ 40) Here is the output: 3.444E+200 -1E+20 1.1E+21 6.66666666666667E+20 1.21576654590569E+19
Summary VB supports 6 numeric operations on integers. The whole number division operator sign is (\). VB supports 5 numeric operations on floating numbers.
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
22
VBScript
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 greater than or equal to the second operand. Less than or equal to ( 9.99999e-1) Msgbox(9.9999e-1 < 1) Msgbox(9.9999e-1 >= 0.99999) Msgbox(1.00000001 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.
24
VBScript 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 the first string is greater than the second string or two strings are equal. Less than or equal to ( "abc") Msgbox("abc" < "abc") Msgbox("abc" >= "abd") Msgbox("abc" 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 "Err.Number
73
VBScript
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. err or. 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 r aise 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 t he host environment, if you don't manage them. "On Error Resume Next" turns on the error handling flag, which causes the host environment environment to continue executing executing the next statement after raising a runtime error. "On Error GoTo 0" turns off the error handling flag, which causes the host environment to stop executing the current procedure after raising a runtime error. The "Err" object is built-in object representing the last runtime error. "Err.Number > 0" can be used to see if a runtime error has occurred or not. "Err.Clear()" method can be used to clear the "Err" object. "Err.Raise()" method can be used to raise your own runtime errors.
74
VBScript
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 O bjects
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 pr ovide 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.
75
VBScript
"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:
76
VBScript ' Repeat matches on the entire string oRegExp.Global = True ' Ignore cases while matching the pattern oRegExp.IgnoreCase = True Now the "RegExp" object, oRegExp, is ready to be used to match again any given string following operations: ' Returns True if the pattern matched at least once. bFound = oRegExp.Test(string) ' Returns a copy of the given string with each match replaced. sCopy = oRegExp.Replace(string, replacement) ' Returns a MatchCollection object containing matches. Set oMatches = oRegExp.Execute(string) Code: Example: .Pattern txt="Automation is fast" Set objReg=CreateObject("vbscript.regexp") objReg.Pattern="i" Msgbox objReg.Replace(txt,"##") Out Put: Automat##on is fast
Summary Regular expression describes one or more strings to match when you search a body of text. The expression serves as a template for matching a character pattern to the string that is being searched. A regular expression consists of ordinary characters (for example, letters a through z) and special characters, as known metacharacters.
Exercise Write Regular expression verifying email address1.
77
View more...
Comments