pu
ga
di
ad
M
ra
nd
ha
C
Page 1 6/9/2014
Working with VB Script
Table of Contents
1. INTRODUCTION .............................................................................................................. 3
2. DATA TYPES .................................................................................................................... 4
3. VARIABLES ...................................................................................................................... 6
4. CONSTANTS ................................................................................................................... 10
5. OPERATORS ................................................................................................................... 12
6. CONDITIONAL STATEMENTS .................................................................................... 14
7. LOOPS .............................................................................................................................. 16
8. BUILT-IN FUNCTIONS .................................................................................................. 20
9. PROCEDURES................................................................................................................. 24
pu
10. REGULAR EXPRESSIONS ............................................................................................ 28
11. VBSCRIPT RUNTIME OBJECTS .................................................................................. 36
ga
di
ad
M
ra
nd
ha
C
Page 2 6/9/2014
Working with VB Script
1. Introduction
VBScript as the name itself suggests, is a scripting language. Scripting languages are
different from programming languages, which an automation engineer does not have to care
much. However from interview point of view it is good to know at least a couple of
differences:
Scripting languages are processed from scratch every time you run them. In other words
scripting languages are not compiled.
Programming languages are compiled languages. Compiled languages (like Java and C) are
processed once and reduced to a simpler form that allows it to run faster than a script that has
to be reprocessed every time.
With some exceptions, software written in programming languages run faster than their
scripting counter parts.
pu
Scripting languages are Easy to learn - compared to traditional programming languages.
ga
It takes much less code to do something with scripting than when using a traditional
di
programming language.
ad
Scripting languages run inside another program. With programming languages, you are
M
writing software that runs independent of an exterior (or parent) program. But, Very popular
programming languages (like Java, C#) run inside a ‘parent’ program - like scripting
ra
languages. Today the difference between scripting and programming is largely an academic
thing. You shouldn’t have to concern yourself with what broad category a particular language
nd
may fall in. You should only be concerned about the language itself and how well suited it is
for the job at hand - each language has its strengths and weaknesses.
ha
This is course is designed to teach you VBScript to efficiently use it in the context of Quick
C
Test Pro. There are many websites that give you very detailed information on how it can be
used for ASP, Windows Script Host etc. It is up to you to decide where you limit yourself in
terms of learning VBScript.
Page 3 6/9/2014
Working with VB Script
2. Data Types
While working with any programming/scripting languages often you need to deal with
different types of values, which are made up of one or more characters. These characters can
be numeric or alphabets or special characters or a combination of these. All these characters
and their combinations can be classified into different types called data types.
In other languages you will encounter lot of data types like, Strings, Integers, Booleans, and
Characters etc. But, the good news with VBScript is that you have only one data type -
‘Variant’. You will understand more about data types while dealing with variables. Basically
any data type can be stored in a variable of type ‘Variant’ Following are examples of data
types that can be stored in a variable of type variant. In a way they are considered as sub-
types of main type ‘Variant’
pu
Subtype Description
ga
Empty Variant is un-initialized. Value is 0 for numeric variables or a zero-length
string ("") for string variables. di
ad
Null Variant intentionally contains no valid data.
M
Date (Time) Contains a number that represents a date between January 1, 100 to
December 31, 9999.
Page 4 6/9/2014
Working with VB Script
characters in length.
At its simplest, a Variant can contain either numeric or string information. A string is any
character or set of characters enclosed between two double quotes. A number is any digit or
combination of digits from 0-9 (not enclosed between quotes).
In VBScript a Variant behaves as a number when you use it in a numeric context and as a
string when you use it in a string context. That is, if you are working with data that looks like
numbers, VBScript assumes that it is numbers and does what is most appropriate for
numbers. Similarly, if you're working with data that can only be string data, VBScript treats
it as string data. You can always make numbers behave as strings by enclosing them in
quotation marks (" ").
pu
You can use conversion functions to convert data from one subtype to another (please see
chapter 8. Built-In Functions).
ga
di
ad
M
ra
nd
ha
C
Page 5 6/9/2014
Working with VB Script
3. Variables
A variable is a named memory location where in you store the data. As the name itself
suggests variable may change during the execution of program. What this means is that the
data that is stored in the named memory location changes not the location itself. In other
words, address dose not change rather what stays at that address may change. You will learn
the exact meaning of this while practicing examples.
Unlike many other languages, VBScript does not force you to declare a variable before using
it. Variable declaration involves specifying following items before using the name of that
variable in any part of the script.
1. Name
2. Data type of the data it holds
3. Scope of the variable
pu
Fortunately you don’t have to declare a variable in VBScript before using it. You can make
up some name on the fly to store some value of any data type. But, this is not generally a
ga
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
di
available to require explicit declaration of all variables. The Option Explicit statement
ad
should be the first statement in your script.
M
You declare variables explicitly in your script using the Dim statement, the Public statement,
and the Private statement. For example:
ra
Private statement variables are available only to the script in which they are declared.
ha
Variables declared with Dim at the script level are available to all procedures within the
C
script. At the procedure level, variables are available only within the procedure.
A variable's scope is determined by where you declare it. When you declare a variable within
a procedure, only code within that procedure can access or change the value of that variable.
It has local scope and is a procedure-level variable. If you declare a variable outside a
procedure, you make it recognizable to all the procedures in your script. This is a script-level
variable, and it has script-level scope.
The lifetime of a variable depends on how long it exists. The lifetime of a script-level
variable extends from the time it is declared until the time the script is finished running. At
procedure level, a variable exists only as long as you are in the procedure. When the
procedure exits, the variable is destroyed. Local variables are ideal as temporary storage
space when a procedure is executing. You can have local variables of the same name in
Page 6 6/9/2014
Working with VB Script
several different procedures because each is recognized only by the procedure in which it is
declared.
As explained before variables can store any type of value, which can be numbers, string of
characters or objects. However there is slight difference in terms of how we assign values to
variable if they are objects.
Examples:
1. Assign a numeric values to a variable
Dim X
X=50
2. Assign a string values to a variable
Dim X
X = “abc123-%@etc”
3. Assign a numeric object to a variable
pu
Dim X
X= Description.Create
ga
Arrays:
di
ad
In VBScript, much of the time, you deal with variables that hold one value at a time.
But, there may be cases when you want to deal with variables that can hold a series of values.
M
In VBScript you can create a variable that can contain a series of values. This is called an
array variable. VBScript has one and two-dimensional arrays. One-dimensional arrays are
ra
convenient to store values say for example values from particular column or row of table.
nd
Where as two-dimensional arrays are convenient to hold values, just like a table, as rows and
columns.
ha
There are different ways in which we can declare arrays. Declaration of an array variable
uses parentheses () following the variable name. An array will have following characteristics
C
1. Name
2. Parentheses
3. Dimension sub-script(s).
4. Each dimension subscript will have a numeric value that indicates the size of the array.
5. Items in the array are stored by indexes. Indexes in a VBScript array are numbers that
begin with 0, incremented by 1 at a time and end with value of the dimension subscript.
So, if the numeric subscript is 10, it means the array stores 11 values. The values in the
array are called elements.
6. In two-dimensional arrays the first dimension is always number of rows and second
dimension represents number of columns.
7. Values to the elements of an array are assigned by index number. Retrieval is also based
on index number.
Page 7 6/9/2014
Working with VB Script
Examples:
1. Dim A (10)
In this example a single dimension array ‘A’ of size 11 elements is declared.
2. Dim my_table (5,6)
In this example a two-dimensional array ‘my_table’ of 5 rows and 6 columns is declared.
3. Following example shows how to assign values to a single dimension array.
Dim my_array(2)
my_array(0)= “abc”
my_array(1)= 123
my_array (2)= “ab-cd”
4. Following example shows how to retrieve first value from an array.
Some_variable= my_array (0)
Note: The value of the numeric sub-script at the time of array declaration represents
upper boundary of the array. If you try to use an index, which is greater than upper
boundary of the array, you will get an array index out of bounds error.
pu
5. Following example shows how to assign values to a two dimensional array.
6. Following example shows how to retrieve value from second row and first column of an
ha
array:
C
Dynamic Arrays:
You can also declare an array whose size changes during the time your script is
running. This is called a dynamic array. For a dynamic array, no size or number of
dimensions is placed inside the parentheses. For example:
Dim my_array ()
To use a dynamic array, you must subsequently use ReDim to determine the number of
dimensions and the size of each dimension. In the following example, ReDim sets the
Page 8 6/9/2014
Working with VB Script
initial size of the dynamic array to 25. A subsequent ReDim statement resizes the array to
30.
Preserve Keyword:
When an array is resized using ReDim, then all the elements stored in the array will go
away. To keep existing values intact at the same time resize the array use the preserve
keyword. In the above example instead of ‘ReDim my_array(30)’, use the following
statement:
pu
ReDim Preserve my_array (30)
ga
There is no limit to the number of times you can resize a dynamic array, although if you
di
make an array smaller, you lose the data in the eliminated elements.
ad
Array Function:
M
VBScript has a function that creates, initializes and returns a variant of type array.
ra
Example:
Dim A
nd
A = Array (10,20,30)
ha
Page 9 6/9/2014
Working with VB Script
4. Constants
A constant is a meaningful name that takes the place of a number or string and never
changes. Constants provide a convenient way to use specific values without actually having
to remember the value itself. There are two types of constants in VBScript.
1. Built-in or Intrinsic constants.
2. User defined constants.
A number of useful constants you can use in your code are built into VBScript. Because
these constants are already defined in VBScript, you don't need to explicitly declare them in
your code. Simply use them in place of the values they represent.
Color Constants Defines eight basic colors that can be used in scripting.
Date and Time Constants Defines date and time constants used by various date and time
functions.
pu
Date Format Constants Defines constants used to format dates and times.
ga
Miscellaneous Constants Defines constants that don't conveniently fit into any other
category.
di
MsgBox Constants Defines constants used in the MsgBox function to describe button
visibility, labeling, behavior, and return values.
ad
String Constants Defines a variety of non-printable characters used in string
manipulation.
M
Tristate Constants Defines constants used with functions that format numbers.
VarType Constants Defines the various Variant subtypes.
ra
nd
Example:
ha
Following code uses one of the message box constants “vbYesNo”, captures the user
C
Dim response
response=InputBox ("ABC",vbYesNo)
If Response=VbYes Then
MsgBox "Yes button was clicked"
Else
MsgBox "No button was clicked"
End If
You create user-defined constants in VBScript using the Const statement. Using the Const
statement, you can create string or numeric constants with meaningful names and assign
them literal values. For example:
Const MyString = "This is my string."
Const MyAge = 49
Page 10 6/9/2014
Working with VB Script
Note that the string literal is enclosed in quotation marks (" "). Quotation marks are the most
obvious way to differentiate string values from numeric values. You represent Date literals
and time literals by enclosing them in number signs (#). For example:
You may want to adopt a naming scheme to differentiate constants from variables. A good
way is to name your constants in all capital letters. Differentiating constants from variables
eliminates confusion as you develop more complex scripts.
pu
ga
di
ad
M
ra
nd
ha
C
Page 11 6/9/2014
Working with VB Script
5. Operators
VBScript has a full range of operators, including arithmetic operators, comparison operators
and logical operators. Following are important types of operators used in VBScript.
pu
Integer division \ Less than or equal to <= Logical Eqv
equivalence
ga
Modulus arithmetic Mod Greater than or equal di >= Logical Imp
to implication
ad
Addition + Object equivalence Is
Subtraction -
M
Operator Precedence:
Some expressions may include more than one operator. Then each part is evaluated and
ha
resolved in a predetermined order called operator precedence. You can use parentheses to
override the order of precedence and force some parts of an expression to be evaluated before
C
others.
When expressions contain operators from more than one category, arithmetic operators are
evaluated first, comparison operators are evaluated next, and logical operators are evaluated
last (displayed in the above table from left to right)
All Comparison operators have equal precedence; that is, they are evaluated in the left-to-
right order in which they appear.
Arithmetic and logical operators are evaluated in the order of precedence as displayed in
above table, top to bottom, with following two exceptions:
1. When multiplication and division occur together in an expression, each operation is
evaluated as it occurs from left to right.
2. Likewise, when addition and subtraction occur together in an expression, each operation
is evaluated in order of appearance from left to right.
Page 12 6/9/2014
Working with VB Script
The string concatenation (&) operator is not an arithmetic operator, but in precedence it falls
after all arithmetic operators and before all comparison operators.
pu
ga
di
ad
M
ra
nd
ha
C
Page 13 6/9/2014
Working with VB Script
6. Conditional statements
Conditional statements are used to programmatically make decisions inside the script.
There are two types of conditional statements available in VBScript.
If...Then...Else statement
Select Case statement
Usage Formats:
If <Expression(s)> Then
‘Statements
End If
--------------------------------
pu
If <Expression(s)> Then
‘Statements
ga
Else
‘Statements di
End If
-------------------------------
ad
If <Expression(s)> Then
‘Statements
M
End If
nd
----------------------------
If <Expression(s)> Then
ha
‘Statements
Else If <Expression(s)> Then
C
‘Statements
Else
‘Statements
End If
Example: A variable ‘value’ should have values from 0-2. Following code verifies the value
and prits out a message accordingly.
If value = 0 Then
MsgBox “Value is Zero”
ElseIf value = 1 Then
MsgBox “value is greater than zero”
ElseIf value = 2 then
Msgbox “Value is equal to its maximum value”
Else
Msgbox "Value out of range!"
End If
Page 14 6/9/2014
Working with VB Script
-----------------------
Example: Following example takes a string as main expression and compares it with three
different strings and prints out result to a message box.
pu
Case "MasterCard"
MsgBox "Master Card"
ga
Case "Visa"
MsgBox "Visa Card"
Case "American Express"
di
MsgBox "Amex Card"
ad
Case Else
MsgBox "No Card"
M
End Select
There is a special case of usage with If conditional statements. If you have only one
ra
statement to be executed and there is no need for Else part, then you can use If condition like
nd
below.
ha
Example:
Dim A, B
A= "ABC"
B= "ABC"
If A=B Then MsgBox "A and B are equal"
Page 15 6/9/2014
Working with VB Script
7. Loops
In programming often it becomes necessary to repeat a set of steps until a condition is met.
VBScript provides more than one way to do that as shown below.
1. Do…Loop
This loop has four variations like below
-----------------------------
Do While <Expression>
‘Statements
Loop
pu
Example:
Dim a
ga
a=0
Do While a<=5
MsgBox "Value of a="& a
di
a=a+1
ad
Loop
-----------------------------
M
Do Until <Expression>
‘Statements
ra
Loop
nd
Dim a
a=0
C
Do Until a=5
MsgBox "Value of a="& a
a=a+1
Loop
-----------------------------
Do
‘Statements
Loop While <Expression>
Example:
Dim a
a=0
Do
MsgBox "Value of a="& a
a=a+1
Loop While a<=5
Page 16 6/9/2014
Working with VB Script
Note: This one and last one are slightly different from the first two. In the first two
variations, execution flow verifies if the condition is true even before entering the loop.
In the last two variations the execution enters into loop, completes one iteration and then
verifies if the condition is true.
-------------------------------
Do
‘Statements
Loop Until <Expression>
Example:
Dim a
a=0
Do
MsgBox "Value of a="& a
pu
a=a+1
Loop Until a=5
ga
Note: This loop executes until a condition becomes true where as the third variation of
di
Do loop executes so long as a condition is true.
ad
-------------------------------
M
2. For…Next
For loops have two variations:
ra
------------------------------------
nd
Next
C
The above loop executes a statement or group of statements a specified number of times.
Example:
For i=1 to 10
MsgBox “Values of i=”&i
Next
The above loop executes a statement or group of statements for each element in an array
or collection
Page 17 6/9/2014
Working with VB Script
Example:
Please note that loops can be nested one inside another. Also there is a facility to break out of
loop using the Exit statement. This statement is used like below:
Often it becomes necessary to break out of a loop when a condition is met. It might be
necessary to use Exit Do or Exit for statements in conjunction with a conditional statement.
pu
This can be done for example like below:
ga
Dim a, b
a=0 di
b=3
ad
Do While a<=5
MsgBox "Value of a="& a
M
a=a+1
If a>b Then
ra
Exit Do
End If
nd
Loop
ha
Dim a, b
a=0
C
b=3
For a=0 To 5
MsgBox "Value of a="& a
If a>b Then
Exit For
End If
Next
3. While...Wend
Page 18 6/9/2014
Working with VB Script
Dim Counter
Counter = 0 ' Initialize variable.
While Counter < 10 ' Test value of Counter.
Counter = Counter + 1 ' Increment Counter.
MsgBox Counter
Wend ' End While loop when Counter > 10.
pu
ga
di
ad
M
ra
nd
ha
C
Page 19 6/9/2014
Working with VB Script
8. Built-in Functions
VBScript has lot of built in functions. Following table provides a list of them with brief
description. There are around 90 such functions. Going through each one of them with
examples is beyond the scope of this course. For more information please see VBScript
reference in QTP Help. Functions that will be used most often are noted in bold italics.
pu
CByte Function Returns an expression that has been converted to a
Variant of subtype Byte.
ga
CCur Function Returns an expression that has been converted to a
Variant of subtype Currency.
di
CDate Function Returns an expression that has been converted to a
ad
Variant of subtype Date.
CDbl Function Returns an expression that has been converted to a
M
Page 20 6/9/2014
Working with VB Script
pu
(multiplied by 100) with a trailing % character.
ga
GetLocale Function Returns the current locale ID value.
GetObject Function Returns a reference to an Automation object from a
di
file.
ad
GetRef Function Returns a reference to a procedure that can be
bound to an event.
M
InputBox Function Displays a prompt in a dialog box, waits for the user
to input text or click a button, and returns the
ha
Page 21 6/9/2014
Working with VB Script
pu
Mid Function Returns a specified number of characters from a
string.
ga
Minute Function Returns a whole number between 0 and 59,
inclusive, representing the minute of the hour.
di
Month Function Returns a whole number between 1 and 12,
ad
inclusive, representing the month of the year.
MonthName Function Returns a string indicating the specified month.
M
Now Function Returns the current date and time according to the
setting of your computer's system date and time.
ha
Page 22 6/9/2014
Working with VB Script
pu
StrComp Function Returns a value indicating the result of a string
ga
comparison.
String Function Returns a repeating character string of the length
di
specified.
ad
StrReverse Function Returns a string in which the character order of a
specified string is reversed.
M
Page 23 6/9/2014
Working with VB Script
pu
ga
di
ad
M
ra
nd
ha
C
9. Procedures
In VBScript, there are two kinds of procedures; the Sub procedure and the Function
procedure
A Sub procedure is a series of VBScript statements (enclosed by Sub and End Sub
statements) that perform actions.
A Sub procedure can take arguments, which may include constants, variables or expressions
that are passed by a calling procedure/statement. It can also accept certain objects as
arguments.
Page 24 6/9/2014
Working with VB Script
A Function procedure is a series of VBScript statements enclosed by the Function and End
Function statements.
A Function procedure is similar to a Sub procedure, but can also return a value.
A Function procedure can take arguments, which may include constants, variables or
expressions that are passed by a calling procedure/statement. It can also accept certain
objects as arguments.
If a Function procedure has no arguments, its Function statement must include an empty set
of parentheses.
A Function returns a value by assigning a value to its name in one or more statements of the
procedure.
pu
Points to remember:
ga
1. Whether there are arguments or not, both Function and Sub procedures must have parenthesis at the time
of declaration. di
2. While calling a Sub procedure that accepts one or more arguments, DO NOT include the arguments in
parenthesis.
ad
3. While calling a function that accepts one or more arguments, the arguments must be enclosed in
parenthesis.
M
4. If a function procedure is written to return a value then the calling statement must capture the returned
value. Other wise the script engine treats it as Sub procedure and throw an error. If a function does not
ra
Examples:
The function procedure given below accepts three arguments (p=Principal amount, t=time in months
and r=rate of interest) calculates interest amount and returns it.
In the following two statements the above function is called and the interest amount is
printed out to a message box:
Page 25 6/9/2014
Working with VB Script
i=CalculateInterest (5000,12,4.1)
MsgBox i
The following code demonstrates the use of Sub procedure and the concept of calling
Function from a Sub. The script in this example accepts user input, validates the user
entered data, calls the CalculateInterest function and captures the returned value into a
variable and print it out to a message box. Please note that the Function, the Sub and the call
to the Sub must all be in the same script.
Sub TakeInput ()
Dim p,t,r,i
p=0
t=0
r=0
i=0
b=True 'Declare a variable to control looping
Do While b=True
pu
p=Inputbox ("Please enter the principal amount:") 'Prompt the user to enter data.
p=Trim(p) 'Remove spaces from either sides of the entered value.
ga
If IsNull(p) or Len(p)=0 Then 'Verify if the entered value is a null or of zero length.
b=True ' if yes keep prompting the user for the valid value di
Else
If IsNumeric(p) Then b=False ‘ if the user entered value is numeric. If yes, loop ends
ad
End If
Loop
M
Do While b=True
nd
IntAmount=CalculateInterest (p,t,r)' Call the function and capture the returned value in to a variable
Page 26 6/9/2014
Working with VB Script
MsgBox IntAmount
End Sub
pu
ga
di
ad
M
ra
nd
ha
C
Page 27 6/9/2014
Working with VB Script
Think about how you search for files on your hard disk. You most likely use the ? and *
characters to help find the files you're looking for. The ? character matches a single character
in a file name, while the * matches zero or more characters. A pattern such as 'data?.dat'
would find the following files:
data1.dat
data2.dat
datax.dat
dataN.dat
Using the * character instead of the ? character expands the number of files found. 'data*.dat'
matches all of the following:
data.dat
pu
data1.dat
data2.dat
ga
data12.dat
datax.dat di
dataXYZ.dat
While this method of searching for files can certainly be useful, it is also very limited. The
ad
limited ability of the ? and * wildcard characters give you an idea of what regular expressions
M
can do, but regular expressions are much more powerful and flexible. Regular expressions
are extremely helpful to create patterns that are way powerful than those that can be made
ra
You make up patterns using a combination of ?, * and other characters like alphanumeric
characters and some other characters like under score etc, then search for files and folders.
ha
Here the characters -? and *, are being referred to as wild cards. But, there are whole a lot of
such characters available in VBScript in the context of regular expressions. Those characters
C
are called Meta characters. Just as we create patterns using ? or * or both to search for files
and folders, we can create any pattern using the meta characters available in VBScript
regular expressions that would be helpful in many contexts.
The following table contains the complete list of Meta characters and their behavior in the
context of regular expressions. You don’t need to remember or dig deep into each one of
them. Just learn as much as given in examples, which cover wide variety of situations.
Character Description
Marks the next character as either a special character, a literal, a
backreference, or an octal escape. For example, 'n' matches the character
\
"n". '\n' matches a newline character. The sequence '\\' matches "\" and "\("
matches "(".
^ Matches the position at the beginning of the input string. If the RegExp
Page 28 6/9/2014
Working with VB Script
pu
most m times. For example, "o{1,3}" matches the first three o's in
{n,m}
"fooooood". 'o{0,1}' is equivalent to 'o?'. Note that you cannot put a space
ga
between the comma and the numbers.
When this character immediately follows any of the other quantifiers (*,
di
+, ?, {n}, {n,}, {n,m}), the matching pattern is non-greedy. A non-greedy
ad
pattern matches as little of the searched string as possible, whereas the
?
default greedy pattern matches as much of the searched string as possible.
M
For example, in the string "oooo", 'o+?' matches a single "o", while 'o+'
matches all 'o's.
ra
Page 29 6/9/2014
Working with VB Script
match is not captured for possible later use. For example 'Windows
(?!95|98|NT|2000)' matches "Windows" in "Windows 3.1" but does not
match "Windows" in "Windows 2000". Lookaheads do not consume
characters, that is, after a match occurs, the search for the next match
begins immediately following the last match, not after the characters that
comprised the lookahead.
Matches either x or y. For example, 'z|food' matches "z" or "food".
x|y
'(z|f)ood' matches "zood" or "food".
A character set. Matches any one of the enclosed characters. For example,
[xyz]
'[abc]' matches the 'a' in "plain".
A negative character set. Matches any character not enclosed. For
[^xyz]
example, '[^abc]' matches the 'p' in "plain".
A range of characters. Matches any character in the specified range. For
[a-z] example, '[a-z]' matches any lowercase alphabetic character in the range 'a'
through 'z'.
A negative range characters. Matches any character not in the specified
pu
[^a-z] range. For example, '[^a-z]' matches any character not in the range 'a'
through 'z'.
ga
Matches a word boundary, that is, the position between a word and a
\b space. For example, 'er\b' matches the 'er' in "never" but not the 'er' in
di
"verb".
ad
Matches a nonword boundary. 'er\B' matches the 'er' in "verb" but not the
\B
'er' in "never".
M
Page 30 6/9/2014
Working with VB Script
pu
Syntax:
To create a regular expression
ga
Dim re
Set re = New RegExp di
To set pattern:
ad
re.Pattern = <pattern>
M
1. Replace
2. Execute
nd
3. Test
ha
1. Global
2. IgnoreCase
--------------------------------------------------------------------------------------------
Example usage of *:
Dim re,s
Set re = New RegExp
re.Pattern = "\zo*"
'The above pattern can find out first occurrence of any sequence of letters that begin with
‘letter 'z' and followed by any number of occurances (0 to any) of character 'o'
s = "These days animals are found mainly in the zoos, rather than forests"
after_replacement= re.Replace(s, "citie")
'The above statement replaces the first sequence of characters that matches the defined
‘pattern.
Page 31 6/9/2014
Working with VB Script
MsgBox after_replacement
----------------------------------------------------------------------------------------
---------------------------------------------------------------------------
Dim re, s
Set re = New RegExp
re.Pattern = "n\b"
'\b is to find out the word boundary.
'The above pattern can find out first occurance of a word that ends with letter 'n' .
'followed by any number of occurances (zero to any) of character 'o'
s = "You will not be treated unless you have pain in full"
pu
s = " Only those who have pain in full will be allowed for treatment"
after_replacement= re.Replace(s, "d")
ga
'The above statement replaces the first sequence of characters that matches the defined
pattern. di
MsgBox after_replacement
ad
---------------------------------------------------------------------------
M
Dim re, s
nd
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
Page 32 6/9/2014
Working with VB Script
re.Pattern = "\d{3}"
'above statement can also be written in any of the following ways
' re.Pattern = "\d\d\d"
're.Pattern = "[0-9][0-9][0-9]"
're.pattern="\d+"
'The above pattern can find out first occurance of a three digit number in the string to be
searched
'followed by any number of occurances (0 to any) of character 'o'
s = "USA received 100 millimeters of rain in the last 2 weeks."
after_replacement= re.Replace(s, "many")
'The above statement replaces the first sequence of
'characters that matches the defined pattern.
MsgBox after_replacement
------------------------------------------------------------------------------------
pu
Dim re, s
Set re = New RegExp
ga
re.Pattern = "(g|m)+ood"
s = "Good tasting mood is usually bad for health!, as such goods often carry fat!"
di
re.Global=True
ad
after_replacement= re.Replace(s, "food")
'The above statement replaces the first sequence of
M
-----------------------------------------------------------------------------------
ha
Page 33 6/9/2014
Working with VB Script
re.IgnoreCase = True
re.pattern="http://w*\.[\w-]*\.\w{3}\b"
s = "Some long string with http://www.abc.com buried in it."
If re.Test(s) Then
MsgBox "Found a URL."
Else
MsgBox "No URL found."
End If
---------------------------------------------------------------
pu
s = "http://www.ChanduUSA-IL.com is a valid web address. And so is "
s = s & vbCrLf & "http://www.ChanduINDIA-AP.com. As is "
ga
s = s & vbCrLf & "http://www.ChanduUK-ABC.com."
Set colMatches = re.Execute(s) di
sMsg = ""
ad
For Each objMatch in colMatches
sMsg = sMsg & "Match of " & objMatch.Value
M
sMsg = sMsg & ", found at position " & objMatch.FirstIndex & " of the string. "
sMsg = sMsg & "The length matched is "
ra
Next
MsgBox "Number of matches found ="&colMatches.count
ha
MsgBox sMsg
C
'-------------------------------------------------------------
Example: Find out all valid employee Ids. Valid Ids will have two alpha character prefix
followed by a hyphen and then by three or four-digit number.
Dim re, objMatch, colMatches, sMsg
Set re = New RegExp
re.GLobal=True
re.Pattern="\w{2}-+\d{3,4}\b"
s="Employee IDs AB-999,BC-99999 and CA-1001 have been deleted from the database"
Set colMatches=re.Execute(s)
nCount=colMatches.Count
MsgBox nCount
For each id in colMatches
MsgBox (id.Value)
Next
Page 34 6/9/2014
Working with VB Script
pu
ga
di
ad
M
ra
nd
ha
C
Page 35 6/9/2014
Working with VB Script
A Dictionary object works somewhat similar to arrays but some times more convenient than
arrays. In arrays we store values in the form of element index and element value. To retrieve
a value from the array we have to use the index. Suppose, you want to retrieve a particular
value from an array, but don’t know its index. In such cases you have to iterate through
elements of the array and during each iteration find out element’s value and verify if it is the
value you wanted. This is long process and you might want question is there some thing in
VBScript, which can be used as array but with string subscripts instead of numeric indexes.
Dictionary object is the solution. Items can be any form of data, and are stored in the array.
Each item is associated with a unique key. The key is used to retrieve an individual item and
is usually a integer or a string
Properties:
pu
1. Count - Returns the number of items in a collection or Dictionary object
ga
2. Item - Sets or returns an item for a specified key in a Dictionary object
3. Key - Sets a key in a Dictionary object. di
Example:
ad
d.Add "UK","London"
Page 36 6/9/2014
Working with VB Script
pu
'Remove a pair of Key-Value
d.Remove("Egypt")
ga
di
'Verify that the key "Egypt "and its value have been removed.
If d.Exists("Egypt") Then
ad
MsgBox d.Item("Egypt")
M
Else
MsgBox "The key Egypt and its value have been removed"
ra
End If
nd
ha
Page 37 6/9/2014
Working with VB Script
As a part of your automation efforts, often it becomes necessary to work with drives, folders
and files like – Create a file/folder, delete a file/folder, move a file or folder, write to or read
from a file etc. You use file system object model for that purpose.
pu
To delete objects, use the DeleteFile and DeleteFolder methods of the FileSystemObject
object, or the Delete method of the File and Folder objects. You can also copy and move
ga
files and folders, by using the appropriate methods.
Note Some functionality in the FileSystemObject object model is
di
redundant. For example, you can copy a file using either the CopyFile method
ad
of the FileSystemObject object, or you can use the Copy method of the File
object. The methods work the same; both exist to offer programming
M
flexibility.
A list of objects and collections in the file system object along with their methods and
ra
Page 38 6/9/2014
Working with VB Script
Object/Collection Description
FileSystemObject Main object. Contains methods and properties that allow you to create, delete, gain information about, and
generally manipulate drives, folders, and files. Many of the methods associated with this object duplicate those in
other FSO objects; they are provided for convenience.
Drive Object. Contains methods and properties that allow you to gather information about a drive attached to the
system, such as its share name and how much room is available. Note that a "drive" isn't necessarily a hard disk,
but can be a CD-ROM drive, a RAM disk, and so forth. A drive doesn't need to be physically attached to the
u
system; it can be also be logically connected through a network.
ap
Drives Collection. Provides a list of the drives attached to the system, either physically or logically. The Drives
collection includes all drives, regardless of type. Removable-media drives need not have media inserted for them
g
to appear in this collection.
di
File Object. Contains methods and properties that allow you to create, delete, or move a file. Also allows you to query
the system for a file name, path, and various other properties.
ad
Files Collection. Provides a list of all files contained within a folder.
Folder Object. Contains methods and properties that allow you to create, delete, or move folders. Also allows you to
M
query the system for folder names, paths, and various other properties.
Folders Collection. Provides a list of all the folders within a Folder.
TextStream ra
Object. Allows you to read and write text files.
nd
ha
reference)
FileSystemObject BuildPath Appends a name to an existing path. Drive Returns a Drives collection consisting of all Drive objects
CopyFile Copies one or more files from one available on the local machine.
location to another.
Page 39 6/9/2014
Working with VB Script
u
DeleteFolder Deletes a specified folder and its
ap
contents
DriveExists Returns True if the specified drive
g
exists; False if it does not
di
FileExists Returns True if a specified file
ad
exists; False if it does not
FolderExists Returns True if a specified folder
M
exists; False if it does not
GetAbsolutePathName Returns a complete
ra
and unambiguous path from a provided path
specification
nd
GetBaseName Returns a string containing the
base name of the last component, less any file
ha
extension, in a path
GetDrive Returns a Drive object corresponding
C
Page 40 6/9/2014
Working with VB Script
containing the extension name for the last
component in a path
GetFile Returns a File object corresponding to
the file in a specified path
GetFileName Returns the last component of
specified path that is not part of the drive
specification
GetFolder Returns a Folder object
u
corresponding to the folder in a specified path
ap
GetParentFolderName Returns a string
containing the name of the parent folder of the
g
last component in a specified path
di
GetSpecialFolder Returns the special folder
ad
object specified (Windows/System/ Temporary)
GetTempName Returns a randomly generated
M
temporary file or folder name that is useful for
performing operations that require a temporary
file or folder
ra
MoveFile Moves one or more files from one
nd
location to another
MoveFolder Moves one or more folders from
ha
Page 41 6/9/2014
Working with VB Script
a network share. Read-only
DriveType Returns a value indicating the type of a specified
drive
FileSystem Returns the type of file system in use for the
specified drive
FreeSpace Returns the amount of free space available to a
user on the specified drive or network share. Read-only
IsReady Returns True if the specified drive is ready; False if it
is not
u
Path Returns the path for a specified file, folder, or drive
RootFolder Returns a Folder object representing the root
ap
folder of a specified drive. Read-only
SerialNumber Returns the decimal serial number used to
g
uniquely identify a disk volume.
di
ShareName Returns the network share name for a specified
drive
ad
TotalSize Returns the total space, in bytes, of a drive or
network share
M
VolumeName Sets or returns the volume name of the specified
drive. Read/write
Drives The Drives collection has no methods. Count Returns the number of items in a collection
File
ra
Copy Copies a specified file or folder from one Attributes Sets or returns the attributes of files or folders.
nd
location to another Read/write or read-only, depending on the attribute
Delete Deletes a specified file. Syntax:
ha
object.Attributes [= newattributes]
Move Moves a specified file from one location
C
Page 42 6/9/2014
Working with VB Script
ReadOnly 1 Read-only file. Attribute is read/write.
Hidden 2 Hidden file. Attribute is read/write.
System 4 System file. Attribute is read/write.
Volume 8 Disk drive volume label. Attribute is read-
only.
Directory 16 Folder or directory. Attribute is read-only.
Archive 32 File has changed since last backup.
Attribute is read/write.
Alias 64 Link or shortcut. Attribute is read-only.
u
Compressed 128 Compressed file. Attribute is read-only.
ap
DateCreated Returns the date and time that the specified file or
g
di
folder was created. Read-only
DateLastAccessed Returns the date and time that the specified
ad
file or folder was last accessed. Read-only
DateLastModified Returns the date and time that the specified
M
file or folder was last modified. Read-only
Drive Returns the drive letter of the drive on which the specified
ra file or folder resides. Read-only
Name Sets or returns the name of a specified file or folder.
nd
Read/write
ParentFolder Returns the folder object for the parent of the
ha
Page 43 6/9/2014
Working with VB Script
the earlier 8.3 file naming convention
Size For files, returns the size, in bytes, of the specified file. For
folders, returns the size, in bytes, of all files and subfolders
contained in the folder
Type Returns information about the type of a file or folder. For
example, for files ending in .TXT, "Text Document" is returned.
Files The Files collection has no methods Count Returns the number of items in a collection
u
Folder Copy Copies a specified folder from one Attributes Sets or returns the attributes of files or folders.
ap
location to another Read/write or read-only, depending on the attribute.
Delete Deletes a specified folder. DateCreated Returns the date and time that the specified file or
g
Move Moves a specified folder from one folder was created. Read-only
di
location to another DateLastAccessed Returns the date and time that the specified
file or folder was last accessed. Read-only
ad
DateLastModified Returns the date and time that the specified
file or folder was last modified. Read-only
M
Drive Returns the drive letter of the drive on which the specified
Page 44 6/9/2014
Working with VB Script
u
contained in the folder
ap
SubFolders Returns a Folders collection consisting of all
folders contained in a specified folder, including those with
g
hidden and system file attributes set
Type Returns information about the type of a file or folder. For
di
example, for files ending in .TXT, "Text Document" is returned
ad
Folders Add Adds a new folder to a Folders collection Count Returns the number of items in a collection
TextStream Close Closes an open TextStream file AtEndOfLine Returns true if the file pointer is positioned
M
Read Reads a specified number of characters immediately before the end-of-line marker in a TextStream file;
ra
from a TextStream file and returns the resulting
string.
false if it is not. Read-only
AtEndOfStream Returns true if the file pointer is at the end of
nd
ReadAll Reads an entire TextStream file and a TextStream file; false if it is not
returns the resulting string Column Read-only property that returns the column number of
ha
ReadLine Reads an entire line (up to, but not the current character position in a TextStream file
including, the newline character) from a Line Read-only property that returns the current line number in
C
Page 45 6/9/2014
Working with VB Script
TextStream file
Write Writes a specified string to a TextStream
file
WriteBlankLines Writes a specified number of
newline characters to a TextStream file
WriteLine Writes a specified string and newline
character to a TextStream file
u
FSO Constants:
ap
You might have to use following built-in constants while working with files.
g
di
Constant Value Description
ForReading 1 Open a file for reading only. You can't write to this file.
ad
ForWriting 2 Open a file for writing. If a file with the same name exists, its previous contents are
overwritten.
M
ForAppending 8 Open a file and write to the end of the file.
Page 46 6/9/2014
Working with VB Script
Option Explicit
Dim FSO
Dim objStream
Const TristateFalse = 0
Const FILE_NAME = "C:\CREATE_FILE_TEST.TXT"
With objStream
.WriteLine "Test Line 1"
.WriteLine "Test Line 2"
pu
.WriteLine "Test Line 3"
.Close
ga
End With
di
MsgBox "Successfully created " & FILE_NAME & "."
ad
Option Explicit
ra
Dim objFSO
nd
Dim objStream
Dim strText
ha
strText = ""
Do While Not objStream.AtEndOfStream
strText = strText & objStream.ReadLine & vbNewLine
Loop
Set objStream = Nothing
Page 47 6/9/2014
Working with VB Script
Option Explicit
Dim FSO
Dim objStream
Const ForAppending = 8
Const TristateFalse = 0
Const FILE_NAME = "C:\CREATE_FILE_TEST.TXT"
pu
With objStream
ga
.WriteLine "Appended Line 1"
.WriteLine "Appended Line 2" di
.WriteLine "Appended Line 3"
ad
.Close
End With
M
End If
nd
ha
Option Explicit
Dim objFSO
Dim objRootFolder
Dim objFileLoop
Dim boolFoundIt
boolFoundIt = False
For Each objFileLoop In objRootFolder.Files
If UCase(objFileLoop.Name) = " CREATE_FILE_TEST.TXT " Then
boolFoundIt = True
Exit For
Page 48 6/9/2014
Working with VB Script
End If
Next
Set objFileLoop = Nothing
Set objRootFolder = Nothing
If boolFoundIt Then
MsgBox "We found your CREATE_FILE_TEST.TXT file in the C:\ directory."
Else
MsgBox "We could not find CREATE_FILE_TEST.TXT in the C:\ directory."
End If
Option Explicit
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
pu
If objFSO.FileExists("C:\ CREATE_FILE_TEST.TXT ") Then
MsgBox "We found your CREATE_FILE_TEST.TXT file in the C:\ directory."
ga
Else
MsgBox "We could not find CREATE_FILE_TEST.TXT in the C:\ directory."
di
End If
ad
Set objFSO = Nothing
M
Option Explicit
nd
Dim FSO
ha
MsgBox "CREATE_FILE_TEST.TXT exists and will be deleted when you click Ok"
FSO.DeleteFile("C:\CREATE_FILE_TEST.TXT")
MsgBox "CREATE_FILE_TEST.TXT has been deleted"
Else
MsgBox "CREATE_FILE_TEST.TXT does not exist"
End If
Page 49 6/9/2014