Вы находитесь на странице: 1из 49

Working with VB Script

Working with VBScript

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

Boolean Contains either True or False.


ra

Byte Contains integer in the range 0 to 255.


nd

Integer Contains integer in the range -32,768 to 32,767.


ha

Currency -922,337,203,685,477.5808 to 922,337,203,685,477.5807.


C

Long Contains integer in the range -2,147,483,648 to 2,147,483,647.

Single Contains a single-precision, floating-point number in the range -


3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to
3.402823E38 for positive values.

Double Contains a double-precision, floating-point number in the range -


1.79769313486232E308 to -4.94065645841247E-324 for negative values;
4.94065645841247E-324 to 1.79769313486232E308 for positive values.

Date (Time) Contains a number that represents a date between January 1, 100 to
December 31, 9999.

String Contains a variable-length string that can be up to approximately 2 billion

Page 4 6/9/2014
Working with VB Script

characters in length.

Object Contains an object.

Error Contains an error number.

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

Public statement variables are available to all procedures in all scripts.


nd

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.

Scope and Lifetime of Variables

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.

Assigning Values to Variables:

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.

Dim my_table (2,3)


ga
di
my_table (1,1) = “First row and first column”
ad
my_table (1,2) = “First row and second column”
my_table (1,3) = “First row and third column”
M

my_table (2,1) = “Second row and first column”


my_table (2,2) = “Second row and second column”
ra

my_table (2,3) = “Second row and third column”


nd

6. Following example shows how to retrieve value from second row and first column of an
ha

array:
C

Some_variable = my_table (2,1)

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.

ReDim my_array (25)

ReDim my_array (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

Now A is an array variable with three elements.


C

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

response and prints it out to a message box.

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:

Const CutoffDate = #6-1-97#

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.

Arithmetic Comparison Logical

Description Symbol Description Symbol Description Symbol

Exponentiation ^ Equality = Logical negation Not

Unary negation - Inequality <> Logical And


conjunction

Multiplication * Less than < Logical disjunction Or

Division / Greater than > Logical exclusion Xor

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

String concatenation &


ra
nd

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.

The Is operator is an object reference comparison operator it checks to determine if two


object references refer to the same object.

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

Else If <Expression(s)> Then


‘Statements
ra

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

-----------------------

Select Case <Main Expression>


Case <Expression1>
‘Statements
Case <Expression2>
‘Statements
Case <Expression3>
‘Statements
Case Else
‘Statements
End Select

Example: Following example takes a string as main expression and compares it with three
different strings and prints out result to a message box.

Select Case "MasterCard"

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

If <Expression> Then ‘Statement


C

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

Note: This loop will execute so long as a condition is true.

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

Note: This loop executes until a condition becomes true


Example:
ha

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

For counter=start to end


‘Statements
ha

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

Following is the second variation of For loop

For Each element In group


‘Statements
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:

Dim AddressString, AddressArray


AddressString="Scalar; USA; Schaumburg;IL;60173"
AddressArray=Split(AddressString,";")
For Each part In AddressArray
MsgBox part
Next

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:

In case of Do…Loops : Exit Do


In case of For…Loops : Exit For

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

Executes a series of statements as long as a given condition is True.


The following example illustrates use of the While...Wend statement:

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.

Abs Function Returns the absolute value of a number.


Array Function Returns a Variant containing an array.
Asc Function Returns the ANSI character code corresponding to
the first letter in a string.
Atn Function Returns the arctangent of a number.
CBool Function Returns an expression that has been converted to a
Variant of subtype Boolean.

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

Variant of subtype Double.


ra

Chr Function Returns the character associated with the specified


ANSI character code.
nd

CInt Function Returns an expression that has been converted to a


Variant of subtype Integer.
ha

CLng Function Returns an expression that has been converted to a


Variant of subtype Long.
C

Cos Function Returns the cosine of an angle.


CreateObject Function Creates and returns a reference to an Automation
object.
CSng Function Returns an expression that has been converted to a
Variant of subtype Single.
CStr Function Returns an expression that has been converted to a
Variant of subtype String.
Date Function Returns the current system date.
DateAdd Function Returns a date to which a specified time interval has
been added.
DateDiff Function Returns the number of intervals between two dates.
DatePart Function Returns the specified part of a given date.
DateSerial Function Returns a Variant of subtype Date for a specified
year, month, and day.

Page 20 6/9/2014
Working with VB Script

DateValue Function Returns a Variant of subtype Date.


Day Function Returns a whole number between 1 and 31,
inclusive, representing the day of the month.
Eval Function Evaluates an expression and returns the result.
Exp Function Returns e (the base of natural logarithms) raised to
a power.
Filter Function Returns a zero-based array containing subset of a
string array based on a specified filter criteria.
Fix Function Returns the integer portion of a number.
FormatCurrency Function Returns an expression formatted as a currency
value using the currency symbol defined in the
system control panel.
FormatDateTime Returns an expression formatted as a date or time.
Function
FormatNumber Function Returns an expression formatted as a number.
FormatPercent Function Returns an expression formatted as a percentage

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

Hex Function Returns a string representing the hexadecimal value


of a number.
ra

Hour Function Returns a whole number between 0 and 23,


inclusive, representing the hour of the day.
nd

InputBox Function Displays a prompt in a dialog box, waits for the user
to input text or click a button, and returns the
ha

contents of the text box.


C

InStr Function Returns the position of the first occurrence of one


string within another.
InStrRev Function Returns the position of an occurrence of one string
within another, from the end of string.
Int Function Returns the integer portion of a number.
IsArray Function Returns a Boolean value indicating whether a
variable is an array.
IsDate Function Returns a Boolean value indicating whether an
expression can be converted to a date.
IsEmpty Function Returns a Boolean value indicating whether a
variable has been initialized.
IsNull Function Returns a Boolean value that indicates whether an
expression contains no valid data (Null).
IsNumeric Function Returns a Boolean value indicating whether an
expression can be evaluated as a number.

Page 21 6/9/2014
Working with VB Script

IsObject Function Returns a Boolean value indicating whether an


expression references a valid Automation object.
Join Function Returns a string created by joining a number of
substrings contained in an array.
LBound Function Returns the smallest available subscript for the
indicated dimension of an array.
LCase Function Returns a string that has been converted to
lowercase.
Left Function Returns a specified number of characters from the
left side of a string.
Len Function Returns the number of characters in a string or the
number of bytes required to store a variable.
LoadPicture Function Returns a picture object. Available only on 32-bit
platforms.
Log Function Returns the natural logarithm of a number.
LTrim Function Returns a copy of a string without leading spaces.

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

MsgBox Function Displays a message in a dialog box, waits for the


ra

user to click a button, and returns a value indicating


which button the user clicked.
nd

Now Function Returns the current date and time according to the
setting of your computer's system date and time.
ha

Oct Function Returns a string representing the octal value of a


number.
C

Replace Function Returns a string in which a specified substring has


been replaced with another substring a specified
number of times.
RGB Function Returns a whole number representing an RGB color
value.
Right Function Returns a specified number of characters from the
right side of a string.
Rnd Function Returns a random number.
Round Function Returns a number rounded to a specified number of
decimal places.
RTrim Function Returns a copy of a string without trailing spaces.
ScriptEngine Function Returns a string representing the scripting language
in use.
ScriptEngineBuildVersion Returns the build version number of the scripting

Page 22 6/9/2014
Working with VB Script

Function engine in use.


ScriptEngineMajorVersion Returns the major version number of the scripting
Function engine in use.
ScriptEngineMinorVersion Returns the minor version number of the scripting
Function engine in use.
Second Function Returns a whole number between 0 and 59,
inclusive, representing the second of the minute.
SetLocale Function Sets the global locale and returns the previous
locale.
Sgn Function Returns an integer indicating the sign of a number.
Sin Function Returns the sine of an angle.
Space Function Returns a string consisting of the specified number
of spaces.
Split Function Returns a zero-based, one-dimensional array
containing a specified number of substrings.
Sqr Function Returns the square root of a number.

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

Tan Function Returns the tangent of an angle.


Time Function Returns a Variant of subtype Date indicating the
ra

current system time.


nd

Timer Function Returns the number of seconds that have elapsed


since 12:00 AM (midnight).
ha

TimeSerial Function Returns a Variant of subtype Date containing the


time for a specific hour, minute, and second.
C

TimeValue Function Returns a Variant of subtype Date containing the


time.
Trim Function Returns a copy of a string without leading or trailing
spaces.
TypeName Function Returns a string that provides Variant subtype
information about a variable.
UBound Function Returns the largest available subscript for the
indicated dimension of an array.
UCase Function Returns a string that has been converted to
uppercase.
VarType Function Returns a value indicating the subtype of a variable.
Weekday Function Returns a whole number representing the day of the
week.
WeekdayName Function Returns a string indicating the specified day of the
week.

Page 23 6/9/2014
Working with VB Script

Year Function Returns a whole number representing the year.

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.

Sub procedure doesn’t return a value.

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.

The return type of a Function is always a Variant.

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

return any value, then there is no need to capture any thing.


5. While calling a function that has no arguments there is no need to use parenthesis (although, it is good
nd

practice to use empty set of parentheses)


6. One function can call other functions; one Sub can call another sub.
ha

7. Also, a Sub can call a function(s) and vice – versa.


C

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.

Function CalculateInterest (p, t, r)


Dim interest ‘Declare a variable
interest=0 ‘Initialize variable
interest=p*t*r/100/12 ‘Calculate interest
CalculateInterest=interest ‘Return calculated amount
End Function

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

'The comments entered above are applicable to following block of code...........................................................


b=True
ra

Do While b=True
nd

r=Inputbox ("Please enter the Interest Rate:")


r=Trim(r)
ha

If IsNull(r) or Len(r)=0 Then


b=True
Else
C

If IsNumeric(r) Then b=False


End If
Loop
'The comments entered above are applicable to following block of code...........................................................
b=True
Do While b=True
t=Inputbox ("Please enter the Time in months:")
t=Trim(t)
If IsNull(t) or Len(t)=0 Then
b=True
Else
If IsNumeric(t) Then b=False
End If
Loop

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

10. Regular Expressions


Unless you have worked with regular expressions before, the term and the concept may be
unfamiliar to you. However, they may not be as unfamiliar as you think.

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

with * and/or ? mentioned above.


nd

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

object's Multiline property is set, ^ also matches the position following


'\n' or '\r'.
Matches the position at the end of the input string. If the RegExp object's
$
Multiline property is set, $ also matches the position preceding '\n' or '\r'.
Matches the preceding subexpression zero or more times. For example,
*
zo* matches "z" and "zoo". * is equivalent to {0,}.
Matches the preceding subexpression one or more times. For example,
+
'zo+' matches "zo" and "zoo", but not "z". + is equivalent to {1,}.
Matches the preceding subexpression zero or one time. For example,
?
"do(es)?" matches the "do" in "do" or "does". ? is equivalent to {0,1}
n is a nonnegative integer. Matches exactly n times. For example, 'o{2}'
{n}
does not match the 'o' in "Bob," but matches the two o's in "food".
n is a nonnegative integer. Matches at least n times. For example, 'o{2,}'
{n,} does not match the "o" in "Bob" and matches all the o's in "foooood".
'o{1,}' is equivalent to 'o+'. 'o{0,}' is equivalent to 'o*'.
m and n are nonnegative integers, where n <= m. Matches at least n and at

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

Matches any single character except "\n". To match any character


.
nd

including the '\n', use a pattern such as '[.\n]'.


Matches pattern and captures the match. The captured match can be
ha

retrieved from the resulting Matches collection, using the SubMatches


(pattern)
collection in VBScript or the $0…$9 properties in JScript. To match
C

parentheses characters ( ), use '\(' or '\)'.


Matches pattern but does not capture the match, that is, it is a non-
capturing match that is not stored for possible later use. This is useful for
(?:pattern)
combining parts of a pattern with the "or" character (|). For example,
'industr(?:y|ies) is a more economical expression than 'industry|industries'.
Positive lookahead matches the search string at any point where a string
matching pattern begins. This is a non-capturing match, that is, the match
is not captured for possible later use. For example 'Windows
(?=95|98|NT|2000)' matches "Windows" in "Windows 2000" but not
(?=pattern)
"Windows" in "Windows 3.1". 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.
Negative lookahead matches the search string at any point where a string
(?!pattern)
not matching pattern begins. This is a non-capturing match, that is, the

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

Matches the control character indicated by x. For example, \cM matches a


\cx Control-M or carriage return character. The value of x must be in the
ra

range of A-Z or a-z. If not, c is assumed to be a literal 'c' character.


nd

\d Matches a digit character. Equivalent to [0-9].


\D Matches a nondigit character. Equivalent to [^0-9].
ha

\f Matches a form-feed character. Equivalent to \x0c and \cL.


\n Matches a newline character. Equivalent to \x0a and \cJ.
C

\r Matches a carriage return character. Equivalent to \x0d and \cM.


Matches any whitespace character including space, tab, form-feed, etc.
\s
Equivalent to [ \f\n\r\t\v].
\S Matches any non-white space character. Equivalent to [^ \f\n\r\t\v].
\t Matches a tab character. Equivalent to \x09 and \cI.
\v Matches a vertical tab character. Equivalent to \x0b and \cK.
Matches any word character including underscore. Equivalent to '[A-Za-
\w
z0-9_]'.
\W Matches any nonword character. Equivalent to '[^A-Za-z0-9_]'.
Matches n, where n is a hexadecimal escape value. Hexadecimal escape
values must be exactly two digits long. For example, '\x41' matches "A".
\xn
'\x041' is equivalent to '\x04' & "1". Allows ASCII codes to be used in
regular expressions.
\num Matches num, where num is a positive integer. A reference back to

Page 30 6/9/2014
Working with VB Script

captured matches. For example, '(.)\1' matches two consecutive identical


characters.
Identifies either an octal escape value or a backreference. If \n is preceded
\n by at least n captured subexpressions, n is a backreference. Otherwise, n is
an octal escape value if n is an octal digit (0-7).
Identifies either an octal escape value or a backreference. If \nm is
preceded by at least nm captured subexpressions, nm is a backreference. If
\nm \nm is preceded by at least n captures, n is a backreference followed by
literal m. If neither of the preceding conditions exists, \nm matches octal
escape value nm when n and m are octal digits (0-7).
Matches octal escape value nml when n is an octal digit (0-3) and m and l
\nml
are octal digits (0-7).
Matches n, where n is a Unicode character expressed as four hexadecimal
\un
digits. For example, \u00A9 matches the copyright symbol (©).

pu
Syntax:
To create a regular expression

ga
Dim re
Set re = New RegExp di
To set pattern:
ad
re.Pattern = <pattern>
M

Regular Expressions methods:


ra

1. Replace
2. Execute
nd

3. Test
ha

Regular Expression Properties:


C

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

----------------------------------------------------------------------------------------

---------------------------------------------------------------------------

Example usage of ‘\b’ the word boundary character

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

Example - Pattern for digits:


ra

Dim re, s
nd

Set re = New RegExp


re.Pattern = "[1234567890]"
ha

'above statement can also be written as re.Pattern = "\d" or as re.Pattern = "[0-9]"


'The above pattern can find out first single digit in the string to be searched
C

'followed by any number of occurances (0 to any) of character 'o'


s = "Spain received 3 millimeters of rain last week."
after_replacement= re.Replace(s, "many")
'The above statement replaces the first sequence of
'characters that matches the defined pattern.
MsgBox after_replacement

--------------------------------------------------------------------------------

--------------------------------------------------------------------------------

Example: Pattern for multiple digits:


Dim re, s
Set re = New RegExp

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

------------------------------------------------------------------------------------

Example – Usage of ‘|’, ( ) and +

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

'characters that matches the defined pattern.


MsgBox after_replacement
ra
nd

-----------------------------------------------------------------------------------
ha

Example usage of Execute method


Dim re, s
C

Set re = New RegExp


re.Global = True
re.pattern="http://w*\.[\w-]*\.\w{3}\b"
s = "http://www.ChanduUSA-IL.com is a valid web address. And so is "
s = s & vbCrLf & "http://www.ChanduINDIA-AP.com. As is "
s = s & vbCrLf & "http://www.ChanduUK-ABC.com."
Set colMatches = re.Execute(s)
For Each match In colMatches
MsgBox "Found URL: " & match.Value
Next
-------------------------------------------------------------------

Example usage of Test method


Dim re, s
Set re = New RegExp

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

---------------------------------------------------------------

Example – Usage of collection properties

Dim re, objMatch, colMatches, sMsg


Set re = New RegExp
re.Global = True
re.pattern="http://w*\.[\w-]*\.\w{3}\b"

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

sMsg = sMsg & objMatch.Length & "." & vbCrLf


nd

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

11. VBScript Runtime Objects


Dictionary Object:

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

Dim d ' Create a variable.


M

Set d = CreateObject("Scripting.Dictionary") ' Create a dictionary object


ra

' Add some keys and items.


nd

d.Add "India", "Delhi"


d.Add "North America", "Washington DC"
ha

d.Add "Egypt", "Cairo"


C

d.Add "UK","London"

'Change the value associated with the key "India"


MsgBox d.Item("India")
d.Item("India")="New Delhi"
MsgBox d.Item("India")

'Change the key from "North America" to "USA"


MsgBox d.Item("North America")
d.Key("North America")="USA"
MsgBox d.Item("USA")

Page 36 6/9/2014
Working with VB Script

'Verify if a particular key exists


If d.Exists("USA") Then
MsgBox d.Item("USA")
End If

'Retrieve all keys into an array


aKeys=d.Keys
For each sKey in aKeys
MsgBox sKey
Next

'Find out number of key-Value pairs in the object


MsgBox d.Count

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

'Find out number of key-Value pairs in the object


MsgBox d.Count
C

'Remove all Items from the object


d.RemoveAll

'Find out number of key-Value pairs in the object


MsgBox d.Count

File System Object:

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.

To program with the FileSystemObject (FSO) object model:


 Use the CreateObject method to create a FileSystemObject object.
 Use the appropriate method on the newly created object.
 Access the object's properties.
First, create a FileSystemObject object by using the CreateObject method.
The following code displays how to create an instance of the FileSystemObject:
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
After creating the file system object, depending on need you use the appropriate method of
the FileSystemObject object. For example, to create a new object, use either
CreateTextFile or CreateFolder (the FSO object model doesn't support the creation or
deletion of drives).

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

properties is given in following tables


nd
ha
C

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

Object/Collection Methods Properties


(For syntax and examples please see VBScript (For syntax and examples please see VBScript reference)
C

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

CopyFolder Recursively copies a folder from


one location to another
CreateFolder Creates a folder
CreateTextFile Creates a specified file name
and returns a TextStream object that can be used
to read from or write to the file
DeleteFile Deletes a specified file

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

to the drive in a specified path.


GetDriveName Returns a string containing the
name of the drive for a specified path
GetExtensionName Returns a string

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

one location to another


OpenTextFile Opens a specified file and returns
C

a TextStream object that can be used to read


from, write to, or append to the file
Drive The Drive object has no methods. AvailableSpace Returns the amount of space available to a
user on the specified drive or network share
DriveLetter Returns the drive letter of a physical local drive or

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

to another The newattributes argument can have any of the following


OpenAsTextStream Opens a specified file and values or any logical combination of the following values:
returns a TextStream object that can be used to
Constant Value Description
read from, write to, or append to the file
Normal 0 Normal file. No attributes are set.

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

specified file or folder. Read-only


C

Path Returns the path for a specified file, folder, or drive


ShortName Returns the short name used by programs that
require the earlier 8.3 naming convention
ShortPath Returns the short path used by programs that require

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

ra file or folder resides. Read-only


Files Returns a Files collection consisting of all File objects
nd
contained in the specified folder, including those with hidden
and system file attributes set
ha

IsRootFolder Returns True if the specified folder is the root


folder; False if it is not
C

Name Sets or returns the name of a specified file or folder.


Read/write
ParentFolder Returns the folder object for the parent of the
specified file or folder. Read-only

Page 44 6/9/2014
Working with VB Script

Path Returns the path for a specified file, folder, or drive


ShortName Returns the short name used by programs that
require the earlier 8.3 naming convention
ShortPath Returns the short path used by programs that require
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

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

TextStream file and returns the resulting string. a TextStream file


Skip Skips a specified number of characters
when reading a TextStream file
SkipLine Skips the next line when reading a

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.

The format argument can have any of the following settings:


ra
nd
Constant Value Description
TristateUseDefault -2 Opens/Creates/Writes the file using the system default.
ha

TristateTrue -1 Opens/Creates/Writes the file as Unicode.


TristateFalse 0 Opens/Creates/Writes the file as ASCII.
C

Page 46 6/9/2014
Working with VB Script

Example: Creating a text file and write some text in it

Option Explicit

Dim FSO
Dim objStream

Const TristateFalse = 0
Const FILE_NAME = "C:\CREATE_FILE_TEST.TXT"

Set FSO = CreateObject("Scripting.FileSystemObject")

Set objStream = FSO.CreateTextFile(FILE_NAME, True, TristateFalse)

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

Example: Reading a text file


M

Option Explicit
ra

Dim objFSO
nd

Dim objStream
Dim strText
ha

Set objFSO = CreateObject("Scripting.FileSystemObject")


C

Set objStream = objFSO.OpenTextFile("C:\CREATE_FILE_TEST.txt")


Set objFSO = Nothing

strText = ""
Do While Not objStream.AtEndOfStream
strText = strText & objStream.ReadLine & vbNewLine
Loop
Set objStream = Nothing

If strText <> "" Then


MsgBox strText
Else
MsgBox "The file is empty."
End If

Page 47 6/9/2014
Working with VB Script

Example: Append text to a file

Option Explicit

Dim FSO
Dim objStream

Const ForAppending = 8
Const TristateFalse = 0
Const FILE_NAME = "C:\CREATE_FILE_TEST.TXT"

Set FSO = CreateObject("Scripting.FileSystemObject")

If Not FSO.FileExists(FILE_NAME) Then


MsgBox "Could not find " & FILE_NAME
Else
Set objStream = FSO.OpenTextFile(FILE_NAME, ForAppending, False, TristateFalse)

pu
With objStream

ga
.WriteLine "Appended Line 1"
.WriteLine "Appended Line 2" di
.WriteLine "Appended Line 3"
ad
.Close
End With
M

MsgBox "Successfully appended to " & FILE_NAME & "."


ra

End If
nd
ha

Example: Find a file in a directory


C

Option Explicit
Dim objFSO
Dim objRootFolder
Dim objFileLoop
Dim boolFoundIt

Set objFSO = CreateObject("Scripting.FileSystemObject")


Set objRootFolder = objFSO.GetFolder("C:\")
Set objFSO = Nothing

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

Example: Find a file in a directory(with out looping)

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

Example: Delete a file


ra

Option Explicit
nd

Dim FSO
ha

Set FSO = CreateObject("Scripting.FileSystemObject")


If FSO.FileExists("C:\CREATE_FILE_TEST.TXT") Then
C

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

Вам также может понравиться