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

VBScript Tutorial

What Is VBScript?
Microsoft Visual Basic Scripting Edition, the newest member of the Visual Basic
family of programming languages, brings active scripting to a wide variety of
environments, including Web client scripting in Microsoft Internet Explorer and Web
server scripting in Microsoft Internet Information Server.
Since VBScript is interpreted, there must be another program that provides the
interpretation service for it. With VBScript, this program is called the 'host'. So,
technically, VBScript is three different languages because what it can do depends
entirely on what the host supports. (Microsoft makes sure that they are virtually
identical, however.) WSH is the host for VBScript that works directly in Windows.
VBScript "Hosts"
if you're just learning about VBScript, it can be kind of confusing to figure out where
it "fits in" in the Microsoft world. For one thing, Microsoft currently offers three
different 'host' for VBScript.
Microsoft provides three 'host' environments for VBScript:
• IE (Internet Explorer) - Microsoft's web browser software
• IIS (Internet Information Server) - Microsoft's web server software
• WSH (Windows Script Host) - A 'host' environment in the Windows
operating system

Another point of confusion is that there are three versions of WSH and two
implementations. Windows 98 and Windows NT 4 implemented version 1.0. Version
2.0 was released with Windows 2000 and the current version is numbered 5.6.
The two implementations are one that works from a DOS command line (called
"CScript" for Command Script) and one that works in Windows (called "WScript").
You can use CScript only in a DOS command window, but it's interesting to note that
much of the real world computer systems administration still works that way. It
might also be confusing to discover that the WScript object is essential to a lot of
code that is normally run in CScript. The example shown later uses the WScript
object, but you can run it with CScript. Just accept it as maybe being slightly odd,
but that's the way it works.

If WSH is installed, you can run a VBScript program by simply double-clicking on any
file that has the vbs extension and that file will be executed by WSH. Or, for even
more convenience, you can schedule when a script will run with Windows Task
Scheduler. In partnership with Task Scheduler, Windows can run WSH and a script
automatically. For example, when Windows starts, or every day at a particular time.
Introducing WSH

• The WSH Environment


• Features of WSH
• Types of Script Files

WSH is not a single file it is a set of components that you can use to run scripts.
These components are present whether you use the Windows Script Host
environment or other script environments, such as Microsoft Windows 2000 Internet
Information Services (IIS). Script files can be run in the WSH environment, whether
the script is written in Visual Basic Scripting Edition or Microsoft JScript®. WSH is
supported on all of the Windows 32-bit operating systems, such as Microsoft
Windows 95, Microsoft Windows 98, Microsoft Windows Millennium Edition (Me),
Microsoft Windows NT® version 4.0, and Windows 2000. WSH version 1.0 shipped
with Windows 98 (Version 1.0). You can download version 2.0 of WSH, and you can
install it on any of these operating systems.

WSH has several components. These components work together to provide the
operating system with the ability to run and interoperate with scripts.

Script Engines
The WSH environment natively supports two scripting languages: Visual Basic
Scripting Edition and JScript. After the scripting host determines the language used
in your scripts, it loads the appropriate script engine and passes your script to it for
execution. WSH includes two different script engines, one for VBScript and one for
JScript, to run scripts that you write in these languages.

Features of WSH

• Small Memory Footprint


• Language-Independent
 can extend it to other script engines
• Script Reuse
• Command-Line Reference

WSH is ideal for non-interactive scripting needs, such as batch, logon, and
administrative scripting. In addition to non-interactive processing, WSH scripts can
involve some degree of user interaction, such as confirming prompts and entering
variable information.
Small Memory Footprint
The low system overhead of running scripts with WSH makes it ideal for your
administrative scripts.
Language-Independent
Although WSH natively supports the Visual Basic Scripting Edition and Jscript
languages, you can extend the environment so that it can run scripts written in other
languages, such as PerlScript.
Script Reuse
By using WSH, you can save your scripts as operating system files. The content of
your script files is plain text. Therefore, you can write and save your script files by
using a simple text editor such as Notepad. After you save the script files, you can
run your scripts many times; you do not need to rewrite code every time you want
to run a certain set of actions. This is a useful feature if you have scripts that must
be run on a regular basis.

Command-Line Reference
Prior to WSH, the only native script language that the Windows operating system
supported was the command language supported though Cmd.exe.

Administrators often construct batch files (.bat) that contain multiple commands.
These commands are still supported and are an important part of the administrator’s
toolset.

An example for how to write a html page using vbscript


Exercise 1
<HTML>
<HEAD>
<TITLE>Working With VBScript</TITLE>
<SCRIPT LANGUAGE="VBScript">
MsgBox "Welcome to my Web page!"
</SCRIPT>
</HEAD>
</HTML>

Exercise 2
<HTML>
<HEAD>
<TITLE>Test Button Events</TITLE>
</HEAD>
<BODY>
<FORM NAME="Form1">
<INPUT TYPE="Button" NAME="Button1" VALUE="Click">
<SCRIPT FOR="Button1" EVENT="onClick" LANGUAGE="VBScript">
MsgBox "Button Pressed!"
</SCRIPT>
</FORM>
</BODY>
</HTML>

Exercise 3

<HTML>
<HEAD>
<TITLE>Working With VBScript: Exercise 1</TITLE>
<SCRIPT LANGUAGE="VBScript">
<!-- Add this to instruct non-IE browsers to skip over VBScript modules.
Sub cmdClickMe_OnClick
MsgBox "A simply example of VBScript in action."
End Sub
-->
</SCRIPT>
</HEAD>

<BODY>
<H1>Your First VBScript Exercise</H1>
<P>By utilizing VBScript you can give your web pages actions.
Click on the button below to see what we mean.</P>

<FORM NAME="frmExercise1">
<INPUT TYPE="Button" NAME="cmdClickMe" VALUE="Click Me">
</FORM>
</BODY>
</HTML>

An example for how to write a VBS File


Step 1:-create a file with .vbs extension
MsgBox "Welcome to my Web page!"

VBScript Variables

Data and Logic


• Literals
• Constants
• Variables
• Explicit and Implicit Declaration
• Operators
• Logical Comparison
What is a Literal?
• Any Static (unchanged) Value that’s typed directly into a script.
• “String” value’s go in double-quotes.
• Hexadecimal value’s start with &H.

What is a Variable?
A variable is a "container" for information you want to store. A variable's value can
change during the script.
You can refer to a variable by name to see its value or to change its value. In
VBScript, all variables are of type variant, which can store different types of data.
Rules for Variable Names:
• Must begin with a letter
• Cannot contain a period (.)
• Cannot exceed 255 characters

Declaring Variables
You can declare variables with the Dim, Public or the Private statement. Like this:

Dim name
Name = some value
Sub cmdVariables_OnClick
Dim Name
Name = InputBox("Enter your name: ")
MsgBox "The name you entered was " & Name
End Sub

Now you have created a variable. The name of the variable is "name". You can also
declare variables by using its name in your script. Like this:

Name = some value

Now you have also created a variable. The name of the variable is "name".
However, the last method is not a good practice, because you can misspell the
variable name later in your script, and that can cause strange results when your
script is running. This is because when you misspell for example the "name" variable
to "nime" the script will automatically create a new variable called "nime". To
prevent your script from doing this you can use the Option Explicit statement. When
you use this statement you will have to declare all your variables with the dim, public
or private statement. Put the Option Explicit statement on the top of your script. Like
this:

Option explicit
Dim name
Name = some value

Assigning Values to Variables


You assign a value to a variable like this:
Name=“Hege”
i=200

The variable name is on the left side of the expression and the value you want to
assign to the variable is on the right. Now the variable "name" has the value "Hege".

Example using HTML


<HTML>
<HEAD>
<TITLE>Working With VBScript: Exercise 1</TITLE>
<SCRIPT LANGUAGE="VBScript">
<!-- Add this to instruct non-IE browsers to skip over VBScript modules.
Sub cmdClickMe _OnClick
Dim Name
Name = InputBox("Enter your name: ")
MsgBox "The name you entered was " & Name
End Sub
-->
</SCRIPT>
</HEAD>

<BODY>
<H1>Your First VBScript Exercise</H1>
<P>By utilizing VBScript you can give your web pages actions.
Click on the button below to see what we mean.</P>

<FORM NAME="frmExercise1">
<INPUT TYPE="Button" NAME="cmdClickMe" VALUE="Click Me">
</FORM>
</BODY>
</HTML>

Example using Application(.VBS)


Dim Name
Name = InputBox("Enter your name: ")
MsgBox "The name you entered was " & Name

Example to calculate unit price using HTML


<HTML>
<HEAD>
<TITLE>Working With VBScript: Exercise 2</TITLE>
<SCRIPT LANGUAGE="VBScript">
<!-- Add this to instruct non-IE browsers to skip over VBScript modules.
Option Explicit

Sub cmdCalculate_OnClick
Dim AmountofTax
Dim CRLF
Dim Message
Dim Subtotal
Dim TABSPACE
Dim TAX_RATE
Dim TotalCost

' Define our constant values.


TAX_RATE = 0.06
CRLF = Chr(13) & Chr(10)
TABSPACE = Chr(9)

' Perform order calculations.


Subtotal = Document.frmExercise2.txtQuantity.Value * Document.frmExercise2.txtUnitPrice.Value
AmountofTax = Subtotal * TAX_RATE
TotalCost = Subtotal + AmountofTax

' Display the results.


Message = "The total for your order is:"
Message = Message & CRLF & CRLF
Message = Message & "Subtotal:" & TABSPACE & "Rs " & Subtotal & CRLF
Message = Message & "Tax:" & TABSPACE & "Rs " & AmountofTax & CRLF
Message = Message & "Total:" & TABSPACE & "Rs " & TotalCost
MsgBox Message,,"Your Total"
End Sub
-->
</SCRIPT>
</HEAD>
<BODY>
<H1>Your Second VBScript Exercise</H1>
<P>
Variables can be used to store and manipulate values. To see a demonstration
of this enter a quantity and unit price in the fields below and click the
"Calculate Cost" button.
</P>
<FORM NAME="frmExercise2">
<TABLE>
<TR>
<TD><B>Quantity:</B></TD>
<TD><INPUT TYPE="Text" NAME="txtQuantity" SIZE=5></TD>
</TR>
<TR>
<TD><B>Unit price:</B></TD>
<TD><INPUT TYPE="Text" NAME="txtUnitPrice" SIZE=5></TD>
</TR>
</TABLE>
<BR>
<INPUT TYPE="Button" NAME="cmdCalculate" VALUE="Calculate Cost">
</FORM>
</BODY>
</HTML>

Example to calculate unit price using Application(.VBS)

Dim AmountofTax
Dim CRLF
Dim Message
Dim Subtotal
Dim TABSPACE
Dim TAX_RATE
Dim txtQuantity
Dim txtUnitPrice
Dim TotalCost

Sub cmdCalculate
' Define our constant values.
TAX_RATE = 0.06
CRLF = Chr(13) & Chr(10)
TABSPACE = Chr(9)

' Perform order calculations.


Subtotal = txtQuantity * txtUnitPrice
AmountofTax = Subtotal * TAX_RATE
TotalCost = Subtotal + AmountofTax

' Display the results.


Message = "The total for your order is:"
Message = Message & CRLF & CRLF
Message = Message & "Subtotal:" & TABSPACE & "Rs " & Subtotal & CRLF
Message = Message & "Tax:" & TABSPACE & "Rs " & AmountofTax & CRLF
Message = Message & "Total:" & TABSPACE & "Rs " & TotalCost
MsgBox Message,,"Your Total"
End Sub

txtQuantity= InputBox("Enter quantity: ")


txtUnitPrice= InputBox("Enter quantity: ")

cmdCalculate

Lifetime of Variables
How long a variable exists is its lifetime.
When you declare a variable within a procedure, the variable can only be accessed
within that procedure. When the procedure exits, the variable is destroyed. These
variables are called local variables. You can have local variables with the same name
in different procedures, because each is recognized only by the procedure in which it
is declared.If you declare a variable outside a procedure, all the procedures on your
page can access it.
The lifetime of these variables starts when they are declared, and ends when the
page is closed.

Array Variables
Sometimes you want to assign more than one value to a single variable. Then you
can create a variable that can contain a series of values. This is called an array
variable. The declaration of an array variable uses parentheses ( ) following the
variable name. In the following example, an array containing 3 elements is declared:
Dim names(2)

The number shown in the parentheses is 2. We start at zero so this array contains 3
elements. This is a fixed-size array. You assign data to each of the elements of the
array like this:

names(0)=“Tove”
names(1)=“Jani”
names(2)=“Stale”

Similarly, the data can be retrieved from any element using the index of the
particular array element you want. Like this:

Mother=names(0)

You can have up to 60 dimensions in an array. Multiple dimensions are declared by


separating the numbers in the parentheses with commas. Here we have a two-
dimensional array consisting of 5 rows and 7 columns:
Dim table(4,6)

Example of how to use arrays using HTML


<HTML>
<HEAD>
<TITLE>Working With VBScript</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="VBScript">
Dim famname(5)
famname(0) = "Jan Egil"
famname(1) = "Tove"
famname(2) = "Hege"
famname(3) = "Stave"
famname(4) = "Kai Jim"
famname(5) = 99+2
for i = 0 to 5
document.write(famname(i) & "<br>")
next
document.write( "<br><br>")
dim v(1,1)
v(0,0) = "Daniel"
v(0,1) = "Ben"
v(1,0) = "Roger"
v(1,1) = 25
document.write(v(0,0) & "<br>")
document.write(v(0,1) & "<br>")
document.write(v(1,0) & "<br>")
document.write(v(1,1) +1 & "<br>")
</SCRIPT>
</BODY>
</HTML>

Creating Dynamic Arrays


‘*************************************************************
**********
‘Script Name: cre_dyn_arrays.vbs
‘Author: Bit
‘Created: 01/17/2003
‘Description: A demonstration of how to resize an array
‘*************************************************************
**********
‘Initialization Section
Option Explicit
Dim strMessage, astrCustomerList, i
strMessage = “Dynamic Array Demonstration” & vbCrLf & vbCrLf
‘Main Processing Section
DimTheArray()
ReDimTheArray()
DisplayResults()
‘Procedure Section
Function DimTheArray()
ReDim astrCustomerList(2)
astrCustomerList(0) = “XYZ Corp.”
astrCustomerList(1) = “ABC Co.”
astrCustomerList(2) = “Acme Inc.”
End Function
Function ReDimTheArray()
ReDim Preserve astrCustomerList(4)
astrCustomerList(3) = “A&B Corp”
astrCustomerList(4) = “ZZZ Enterprises”
End Function
Function DisplayResults()
For Each i In astrCustomerList
strMessage = strMessage & i & vbCrLf
Next
MsgBox strMessage, , “Resizing an Array” & Space(25)
End Function

Documenting VBScripts with Comments


Comments provide the ability to make scripts self-documenting, making them easier
for others to support. You can add comments to VBScripts using the Rem statement.
The syntax for the Rem statement is shown below. Rem comments

For example, the Rem statement can be used as demonstrated below.

Rem The VBScript MsgBox() function displays text messages


MsgBox “Greetings!”

Alternatively, you can substitute the single quotation mark (‘) character for the
Rem keyword as shown below.

‘ The VBScript MsgBox() function displays text messages


MsgBox “Greetings!”

VBScript Functions

VBScript Procedures
In VBScript the “function”s are actually called “procedure”s.
We have two kinds of procedures: The Sub procedure and the Function procedure.

A Sub procedure:

• is a series of statements, enclosed by the Sub and End Sub


statements.
• can perform actions, but does not return a value .
• can take arguments that are passed to it by a calling procedure .
• without arguments, must include an empty set of parentheses () .

sub mysub()
some statements
end sub

or

sub mysub(argument1,argument2)
some statement
end sub

A Function procedure:
• is a series of statements, enclosed by the Function and End Function
statements
• can perform actions and can return a value
• can take arguments that are passed to it by a calling procedure
• without arguments, must include an empty set of parentheses ()
• returns a value by assigning a value to its name

Function myfunction()
Some statements
Myfunction=some value
End function

Or

Function myfunction(argument1,argument2)
Some statements
Myfunction=some value
End function

Call a Sub or Function Procedure


When you call a Function in your code, you do like this:
name=findname()

Here you call a Function called "findname", the Function returns a value that will be
stored in the variable "name".
Or, you can do like this: Here you also call a Function called "findname", the
Function returns a value that will be displayed in the message box.
Msgbox “your name is “ & findname()

When you call a Sub procedure you can use the Call statement, like this:
Call myproc(argument)
Or, you can omit the Call statement, like this:
Myproc argument
VBScript Conditional Statements

Conditional Statements
Very often when you write code, you want to perform different actions for different
decisions. You can use conditional statements in your code to do this.
In VBScript we have three conditional statements:
• if...then...else statement - use this statement if you want to select
one of two sets of lines to execute
• if...then...elseif statement - use this statement if you want to select
one of many sets of lines to execute
• select case statement - use this statement if you want to select one of
many sets of lines to execute

If....Then.....Else
You should use the If...Then...Else statement if you want to
• execute some code if a condition is true
• select one of two blocks of code to execute If you want to execute
only one statement when a condition is true, you can write the code
on one line:
If 1=10 Then msgbox “Hello”

There is no ..else.. in this syntax. You just tell the code to perform one action if the
condition is true (in this case if i=10).
If you want to execute more than one statement when a condition is true, you must
put each statement on separate lines and end the statement with the keyword "End
If":
If 1=10 Then
msgbox “Hello”
i=i+1
end if

There is no ..else.. in this syntax either. You just tell the code to perform multiple
actions if the condition is true.
If you want to execute a statement if a condition is true and execute another
statement if the condition is not true, you must add the "Else" keyword:

If 1=10 Then
msgbox “Hello”
else
msgbox “Good bye”
end if

The first block of code will be executed if the condition is true, and the other block
will be executed otherwise (if i is not equal to 10).

A Web page that uses the If…Then control structure.


<HTML>
<HEAD>
<TITLE>Bharathi Info Tech-VBScript - If-Then Sample</TITLE>
</HEAD>
<BODY>
<H1
<EM>Using the If-Then Statement</EM></H1>
<HR>
<P>Enter your age and click on the "Evaluate" button. Visual Basic
Script will use the If-Then conditional to show a message depending on
the age you enter.

<PRE>
I am <INPUT NAME="txtAge" SIZE=10 > years old. --
<INPUT TYPE="BUTTON" VALUE="Evaluate" SIZE=30 NAME="cmdEvaluate">
</PRE>

<HR>

<center>
from <em>Bharathi info tech</em> by
</center>

<SCRIPT LANGUAGE="VBScript">
<!-- Option Explicit

Sub cmdEvaluate_OnClick()

Dim Age

Age = CInt(txtAge.Value)

If Age <= 0 or Age > 120 Then


MsgBox "Either you're not born yet or you're getting
too old for this stuff!"
Else
MsgBox "You are " & Age & " years old."
End If

End Sub

-->
</SCRIPT>

</BODY>
</HTML>

If....Then.....Elseif
You can use the if...then...elseif statement if you want to select one of many blocks
of code to execute:
If payment=“cash” Then
Msgbox “You are going to pay cash”
else If payment=“visa” Then
Msgbox “You are going to pay with visa”
else If payment=“Amex” Then
Msgbox “You are going to pay with American express”
else
Msgbox “Unknown method of payment”
end if
<SCRIPT LANGUAGE="VBScript">
<!-- Option Explicit

Sub cmdTest_OnClick()

Dim Age

Age = CInt(txtAge.Value)

If Age = 0 Then
MsgBox "Welcome to the human race!"
ElseIf Age < 0 Then
MsgBox "We hate to say this, but you have to grow up a bit before you start using VBScript!"
ElseIf Age > 0 and Age < 10 Then
MsgBox "If you're bold enough, you must be old enough."
ElseIf Age > 120 Then
MsgBox "You're getting too old for this stuff!"
Else
MsgBox "You're at the perfect age to get started!"
End If

End Sub

-->
</SCRIPT>

Select Case
You can also use the SELECT statement if you want to select one of many blocks of
code to execute:
Select case payment
case “cash”
msgbox “You are going to pay by Cash”
case “visa”
msgbox “You are going to pay with Visa”
case “Amex”
msgbox “You are going to pay with American Express”
case else
msgbox “Unknown method of payment”
end select

This is how it works: First we have a single expression (most often a variable), that
is evaluated once. The value of the expression is then compared with the values for
each Case in the structure. If there is a match, the block of code associated with that
Case is executed.

A Web page that uses the Select control structure.


<HTML>

<HEAD>
<TITLE>Select Case Sample</TITLE>
</HEAD>

<BODY>
<H1<EM>Using the Select Case Structure</EM></h1>

<HR>

<P>Enter your area code and click the 'Check' button. VBScript will
determine the closest dealership nearest you.

<PRE>
<INPUT NAME="txtAreaCode" SIZE=5 > <INPUT TYPE="BUTTON" VALUE="Check"
SIZE=30 NAME="cmdCheck">
</PRE>

<HR>

<center>
From <em>Bharathi info tech</em

</center>

<SCRIPT LANGUAGE="VBScript">
<!-- Option Explicit
Sub cmdCheck_OnClick()
Dim AreaCode
Dim DealerLocation

' Make sure user has supplied input


if Not IsNumeric(txtAreaCode.Value) then
msgbox "You must supply an area code!",0,"No area code given"
exit sub
end if

AreaCode = CInt(txtAreaCode.Value)

Select Case AreaCode


Case 616
DealerLocation = "Grand Rapids"
Case 313
DealerLocation = "Detroit"
Case 517
DealerLocation = "Lansing"
Case 810
DealerLocation = "Pontiac"
Case 906
DealerLocation = "Marquette"
Case Else
DealerLocation = "unknown"

End Select
MsgBox "The closest dealership to you is in " & DealerLocation

End Sub
-->
</SCRIPT>
</BODY>

</HTML>

VBScript Looping Statements

Looping Statements
Very often when you write code, you want to allow the same block of code to run a
number of times. You can use looping statements in your code to do this.
In VBScript we have four looping statements:
• For...Next statement - runs statements a specified number of times.
• For Each...Next statement - runs statements for each item in a
collection or each element of an array
• Do...Loop statement - loops while or until a condition is true
• While...Wend statement - Do not use it -use the Do...Loop statement
instead

For...Next
You can use a For... Next statement to run a block of code, when you know how
many repetitions you want.
You can use a counter variable that increases or decreases with each repetition of
the loop, like this:

for i=1 to 10
Some code
Next

The For statement specifies the counter variable (i) and its start and end values. The
Next statement increases the counter variable (i) by one. Step Keyword Using the
Step keyword, you can increase or decrease the counter variable by the value you
specify.
In the example below, the counter variable (i) is increased by two each time the loop
repeats.
for i=1 to 10 step 2
Some code
Next

To decrease the counter variable, you must use a negative Step value. You must
specify an end value that is less than the start value.
In the example below, the counter variable (i) is decreased by two each time the
loop repeats.
for i=10 to 2 step -2
Some code
Next

Using the For…Next statement in a Web page.


<SCRIPT LANGUAGE="VBScript">
<!-- Option Explicit

Dim Count
Dim Scores(10)
Count = 0
Sub cmdNext_OnClick()
Dim Score
Dim i
Score = CSng(txtScore.Value)
If Count > 9 Then
MsgBox "You can only enter up to 10 scores. Click the Finished button to calculate the
average."
Else
Scores(Count) = Score
Count = Count + 1
txtScore.Value = ""
End If

End Sub

Sub cmdFinished_OnClick()

Dim Average
Dim Sum
Dim i

For i = 0 to Count-1
Sum = Sum + Scores(i)
Next

Average = Sum / Count


txtAverage.Value = Average

Count = 0

End Sub

-->
</SCRIPT>

Exit a For...Next
You can exit a For...Next statement with the Exit For keyword.

Using the For…Next statement in a Web page with additional error-checking to


prevent a divide-by-zero error.
<SCRIPT LANGUAGE="VBScript">
<!-- Option Explicit

Dim Count
Dim Scores(10)

Count = 0

Sub cmdNext_OnClick()
Dim Score
Dim i

Score = CSng(txtScore.Value)

If Count > 9 Then


MsgBox "You can only enter up to 10 scores. Click the Finished
button to calculate the average."
Else
Scores(Count) = Score
Count = Count + 1
txtScore.Value = ""
End If

End Sub

Sub cmdFinished_OnClick()

Dim Average
Dim Sum
Dim i

If Count = 0 Then
MsgBox "You must enter some scores before they can be averaged."
Exit Sub
End If

For i = 0 to Count-1
Sum = Sum + Scores(i)
Next

Average = Sum / Count


txtAverage.Value = Average

Count = 0

End Sub

-->
</SCRIPT>

For Each...Next
A For Each...Next loop repeats a block of code for each item in a collection, or for
each element of an array.
The For Each...Next statement looks almost identical to the For...Next statement.
The difference is that you do not have to specify the number of items you want to
loop through.
Dim names(2)
names(0)=“Tove”
names(1)=“Jani”
names(2)=“Stale”
for each x in names
document.write(x & “<br>“)
next

Do...Loop
You can use Do...Loop statements to run a block of code when you do not know how
many repetitions you want. The block of code is repeated while a condition is true or
until a condition becomes true.
Repeating Code While a Condition is True
You use the While keyword to check a condition in a Do...Loop statement.

Do while i>10
Some code
Loop

If i equals 9, the code inside the loop above will never be executed.

Do
Some code
Loop while i>10

The code inside this loop will be executed at least one time, even if i is less than 10.
Repeating
A Web page that uses the Do While…Loop structure.
<SCRIPT LANGUAGE="VBScript">
<!-- Option Explicit

Sub cmdGetScores_OnClick()

Dim Count
Dim Scores(10)
Dim Score
Dim Average
Dim Sum
Dim i

Score = 0

Do While Score <> "" And Count < 10


Score = InputBox("Enter the next golf score
(Press Return to quit): ")
If Score <> "" Then
Count = Count + 1
Scores(Count-1) = CSng(Score)
End If
Loop

For i = 0 to Count-1
Sum = Sum + Scores(i)
Next

Average = Sum / Count


txtAverage.Value = Average

Count = 0

End Sub

-->
</SCRIPT>

A Web page that uses the Do…Loop While structure.


<SCRIPT LANGUAGE="VBScript">
<!-- Option Explicit

Sub cmdGetScores_OnClick()

Dim Scores(10)
Dim Score
Dim Average
Dim Sum
Dim i

Do
Score = InputBox("Enter the next golf score
(Press Return to quit): ")
If Score <> "" Then
Count = Count + 1
Scores(Count-1) = CSng(Score)
End If
Loop While Score <> "" And Count < 10

For i = 0 to Count-1
Sum = Sum + Scores(i)
Next

Average = Sum / Count

txtAverage.Value = Average

Count = 0

End Sub

-->
</SCRIPT>
Code Until a Condition Becomes True
You use the Until keyword to check a condition in a Do...Loop statement.
Do until i=10
Some code
Loop

If i equals 10, the code inside the loop will never be executed.
Do
Some code
Loop until i=10

The code inside this loop will be executed at least one time, even if i is equal to 10.
Exit a Do...Loop
You can exit a Do...Loop statement with the Exit Do keyword.
Do until i=10
i=i-1
if i<10 Then Exit Do
loop

The code inside this loop will be executed as long as i is different from 10, and as
long as i is greater than 10.

A Web page that uses the Do Until…Loop structure.


<SCRIPT LANGUAGE="VBScript">
<!-- Option Explicit

Sub cmdGetScores_OnClick()

Dim Count
Dim Scores(10)
Dim Score
Dim Average
Dim Sum
Dim i

Score = 0

Do Until Score = "" Or Count > 9


Score = InputBox("Enter the next golf score
(Press Return to quit): ")
If Score <> "" Then
Count = Count + 1
Scores(Count-1) = CSng(Score)
End If
Loop

For i = 0 to Count-1
Sum = Sum + Scores(i)
Next

Average = Sum / Count

txtAverage.Value = Average

Count = 0

End Sub

-->
</SCRIPT>
A Web page that uses the Do…Loop Until structure.
<SCRIPT LANGUAGE="VBScript">
<!-- Option Explicit

Sub cmdGetScores_OnClick()

Dim Count
Dim Scores(10)
Dim Score
Dim Average
Dim Sum
Dim i
Do
Score = InputBox("Enter the next golf score (Press Return to quit): ")
If Score <> "" Then
Count = Count + 1
Scores(Count-1) = CSng(Score)
End If
Loop Until Score = "" Or Count > 9
For i = 0 to Count-1
Sum = Sum + Scores(i)
Next
Average = Sum / Count
txtAverage.Value = Average
Count = 0
End Sub
-->
</SCRIPT>

While…Wend
The While...Wend statement can be used to create a loop that executes as long as a
condition remains true. The syntax for this statement is outlined below.

While condition
statements
Wend

condition is an expression that is being tested, and statements represents VBScript


statements that will be executed during each iteration of the loop. The While...Wend
statement is provided for backward compatibility purposes. Its continued use is
discouraged. Its functionality is duplicated by the Do...While and Do...Until
statements, which are more flexible in their application.

A Web page that uses the While…Wend Until structure.


<HTML>
<HEAD>
<TITLE>Script 3.3 - A While...Wend example</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE=“VBScript”>
Dim intCounter, strDisplayString
intCounter = 1
strDisplayString = “Watch me count to 10” & vbCrLf & vbCrLf
While intCounter <= 10
strDisplayString = strDisplayString & intCounter & vbCrLf
intCounter = intCounter + 1
Wend
alert strDisplayString
</SCRIPT>
</BODY>
</HTML>

VBSCRIPT KEYWORDS

Keyword Description
Empty Used to indicate an uninitialized variable value. A variable
value is uninitialized when it is first created and no value is
assigned to it, or when a variable value is explicitly set to
empty.
dim x 'the variable x is uninitialized! x="ff" 'the variable x
is NOT uninitialized anymore x=empty 'the variable x is
uninitialized!

Note: This is not the same as Null!!


False Has a value equal to 0
Used to disassociate an object variable from an object to
Nothing
release system
resources.

Example: set myObject=Nothing


Null Used to indicate that a variable contains no valid data.

Note: This is not the same as Empty!!


True Has a value equal to -1

VBScript Built-in Functions (partial) Some useful VBScript built-in functions:


Conversion Functions
Function Description
Asc Converts the first letter in a string to ANSI code
CBool Converts an expression to a variant of subtype Boolean
CByte Converts an expression to a variant of subtype Byte
CCur Converts an expression to a variant of subtype Currency
Converts a valid date and time expression to the variant of
CDate
subtype Date
CDbl Converts an expression to a variant of subtype Double
Chr Converts the specified ANSI code to a character
CInt Converts an expression to a variant of subtype Integer
CLng Converts an expression to a variant of subtype Long
CSng Converts an expression to a variant of subtype Single
CStr Converts an expression to a variant of subtype String
Hex Returns the hexadecimal value of a specified number
Oct Returns the octal value of a specified number

Example of CInt function:


The CInt function converts an expression to a variant of subtype Integer.
Note: The value must be a number between -32768 and 32767. Syntax
Cint(expression)
Parameter Description
Expression Required. Any valid expression

Example 1
Dim a
A=134.345
Document.write(Cint (a))
Output:
134

Example 2
Dim a
A=-30000.24
Document.write(Cint (a))
Output:
-30000

Math Functions
Function Description
Abs Returns the absolute value of a specified number
Atn Returns the arctangent of a specified number
Cos Returns the cosine of a specified number (angle)
Exp Returns e raised to a power
Hex Returns the hexadecimal value of a specified number
Int Returns the integer part of a specified number
Fix Returns the integer part of a specified number
Log Returns the natural logarithm of a specified number
Oct Returns the octal value of a specified number
Returns a random number less than 1 but greater or equal
Rnd
to 0
Returns an integer that indicates the sign of a specified
Sgn
number
Sin Returns the sine of a specified number (angle)
Sqr Returns the square root of a specified number
Tan Returns the tangent of a specified number (angle)
Example of Rnd function:
The Rnd function returns a random number. The number is always less than 1 but
greater or equal to 0.
Syntax
Rnd[(number)]
Parameter Description
Number Optional. A valid numeric expression

If number is:
<0 – Rnd returns the same number every time
>0 – Rnd returns the next number in the sequence
=0 – Rnd returns the most recently generated number
Not supplied – Rnd returns next random number in the sequence

Example 1
Document.write(Rnd)
Output:
0.7055475

Example 2
Randomize
Document.write(Rnd)
Output:
0.4758112

Example 3
‘Here is how to produce random integers in a
‘given numder
Dim max,min
Max=100
Min=1
Document.write(Int((max-min+1)*Rnd+min))
Output:
71
String Functions
Function Description
Returns the position of the first occurrence of one string
InStr
within another.
The search begins at the first character of the string
Returns the position of the first occurrence of one string
InStrRev
within another.
The search begins at the last character of the string
LCase Converts a specified string to lowercase
Returns a specified number of characters from the left side
Left
of a string
Len Returns the number of characters in a string
LTrim Removes spaces on the left side of a string
RTrim Removes spaces on the right side of a string
Removes spaces on both the left and the right side of a
Trim
string
Mid Returns a specified number of characters from a string
Replaces a specified part of a string with another string a
Replace
specified
number of times
Returns a specified number of characters from the right
Right
side of a string
Returns a string that consists of a specified number of
Space
spaces
Compares two strings and returns a value that represents
StrComp
the result of
the comparison
Returns a string that contains a repeating character of a
String
specified length
StrReverse Reverses a string
UCase Converts a specified string to uppercase

Example of StrComp function:


The StrComp function compares two strings and returns a value that represents the
result of the comparison.
The StrComp function can return the following values:
• If string1 < string2 - StrComp returns -1
• If string1 = string2 - StrComp returns 0
• If string1 > string2 - StrComp returns 1
• If string1 or string2 is Null - StrComp returns Null

Syntax Example 1
Strcomp(String1,string2[,compare])

Parameter Description
string1 Required. A string expression
string2 Required. A string expression
compare Optional. Specifies the string comparison to use. Default is 0

Can have one of the following values:


0 = vbBinaryCompare - Perform a binary comparison
1 = vbTextCompare - Perform a textual comparison

Example 1
Document.write(strcomp(“VBScript”, “VBScript”))
Output: 0
Example 2
Document.write(strcomp(“VBScript”, “vbscript”))
Output: -1
Example 3
Document.write(strcomp(“VBScript”, “vbscript”,1))
Output: 0
Controlling Variable Scope
‘*************************************************************************
‘Script Name: Script 4.1.vbs
‘Author: Bit
‘Created: 01/04/2003
‘Description: This script demonstrates global and local variable scopes
‘*************************************************************************
‘Initialization Section
Option Explicit
Dim X, Y
‘Main Processing Section
X = 10
GetNewNumber()
MsgBox “X = “ & X & “ Y = “ & Y
‘Procedure Section
Function GetNewNumber()
Dim Y
Y = 20
End Function

‘*************************************************************************
‘Script Name: Script 5.5.vbs
‘Author: Bit
‘Created: 01/17/2003
‘Description: Resizing a dynamic array based on user input
‘*************************************************************************
‘Initialization Section
Option Explicit
Dim strUserInput, strMessage
ReDim astrCustomerList(0)
‘Main Processing Section
CollectInputData()
ProcessInputData()
‘Procedure Section
Function CollectInputData()
Dim i
i=0
Do While UCase(strUserInput) <> “QUIT”
strUserInput = InputBox(“Type a customer name”)
If UCase(strUserInput) <> “QUIT” Then
astrCustomerList(i) = strUserInput
Else
Exit Do
End If
i=i+1
ReDim Preserve astrCustomerList(i)
Loop
End Function
Function ProcessInputData()
Dim i
i=0
For Each i In astrCustomerList
strMessage = strMessage & i & vbCrLf
Next
MsgBox strMessage
End Function

Files and Folders related Functions


VBScript Runtime Properties
Like the objects in the WSH core object model, VBScript runtime objects provide an
extensive supply of properties. You can use the properties to view or change
numerous file system attributes. These properties are listed here.
• AtEndOfLine. Returns a value of either true or false depending on whether the
file pointer precedes the TextStream file’s end-of-line marker.
• AtEndOfStream. Returns a value of either true or false depending on whether
the end of aTextStream file has been reached.
• Attributes. Retrieves or sets file and folder attributes.
• AvailableSpace. Retrieves the amount of free space available on a drive.
• Column. Retrieves the current column position within a TextStream file.
• CompareMode. Retrieves or sets the comparison mode used to compare
a Dictionary object’s string keys.
• Count. Returns a count of the items in a collection or Dictionary object.
• DateCreated. Returns a file or folder’s creation date and time.
• DateLastAccessed. Returns the date and time that a file or folder was last
accessed.
• DateLastModified. Returns the date and time that a file or folder was last
modified.
• Drive. Returns the drive letter representing the drive where a file or folder is
stored.
• DriveLetter. Returns a drive’s drive letter.
• Drives. Creates a Drives collection representing the computer’s Drive objects.
• DriveType. Returns a value indicating a drive’s type.
• Files. Creates a Files collection representing the File objects stored inside a
folder.
• FileSystem. Returns the file system type implemented on a drive.
• FreeSpace. Returns the amount of free space available to the user on a
drive.
• IsReady. Returns a value of either true or false depending on whether a drive
is available.
• IsRootFolder. Returns a value of either true or false identifying whether a
folder is the root folder.
• Item. Retrieves or sets an item based on the specified Dictionary object key.
• Key. Sets a Dictionary object key.
• Line. Returns the current line number in the TextStream file.
• Name. Retrieves or sets a file or folder’s name.
• ParentFolder. Retrieves a file or folder’s parent folder object.
• Path. Retrieves the path associated with a file, folder, or drive.
• RootFolder. Retrieves the Folder object associated with the root folder on the
specified drive.
• SerialNumber. Retrieves a disk volume’s serial number.
• ShareName. Retrieves a network drive’s share name.
• ShortName. Retrieves a file’s or folder’s 8.3 character short name.
• ShortPath. Retrieves the short path associated with a file’s or folder’s 8.3
character name.
• Size. Retrieves a file’s or folder’s byte size.
• SubFolders. Establishes a Folders collection consisting of all the folders
located inside a specified folder.
• TotalSize. Returns the total number of bytes left on a drive.
• Type. Retrieves information about a file’s or folder’s type.
• VolumeName. Retrieves or sets a drive’s volume name.

VBScript Runtime Methods


The methods that belong to the VBScript runtime objects are listed here.

• VBScript Run-time Methods


• Add (Dictionary). Adds a key and item pair to a Dictionary object.
• Add (Folders). Adds a Folder to a collection.
• BuildPath. Appends a name to the path.
• Close. Closes an open TextStream file.
• Copy. Copies a file or folder.
• CopyFile. Copies one or more files.
• CopyFolder. Recursively copies a folder.
• CreateFolder. Creates a new folder.
• CreateTextFile. Creates a file and a TextStream object that can be used to
read and write to the file.
• Delete. Deletes a file or folder.
• DeleteFile. Deletes a file.
• DeleteFolder. Deletes a folder’s contents.
• DriveExists. Returns either true or false depending on the existence of a
drive.
• Exists. Returns either true or false depending on whether a key exists in
a Dictionary object.
• FileExists. Returns either true or false depending on whether a file can be
found.
• FolderExists. Returns a value of true or false depending on whether a folder
can be found.
• GetAbsolutePathName. Returns a complete path name.
• GetBaseName. Retrieves a filename less its file extension.
• GetDrive. Returns the Drive object associated with the drive in the specified
path.
• GetDriveName. Retrieves the name of a drive.
• GetExtensionName. Retrieves a file’s extension.
• GetFile. Retrieves a File object.
• GetFileName. Retrieves the last filename or folder of the specified path.
• GetFileVersion. Retrieves a file’s version number.
• GetFolder. Retrieves the Folder object associated with the folder in the
specified path.
• GetParentFolderName. Retrieves the name of the parent folder.
• GetSpecialFolder. Retrieves a special folder’s name.
• GetTempName. Retrieves the name of a temporary file or folder.
• Items. Returns an array containing the items in a Dictionary object.
• Keys. Returns an array containing the keys in a Dictionary object.
• Move. Moves a file or folder.
• MoveFile. Moves one or more files.
• MoveFolder. Moves one or more folders.
• OpenAsTextStream. Opens a file and returns a TextStream object that can be
used to reference the file.
• OpenTextFile. Opens a file and returns a TextStream object that can be used
to reference the file.
• Read. Returns a string containing x number of characters from
a TextStream file.
• ReadAll. Reads the whole TextStream file and returns its contents.
• ReadLine. Reads a line in a TextStream file.
• Remove. Deletes a Dictionary object’s key, item pair.
• Skip. Skips x number of character positions when processing
a TextStream file.
• SkipLine. Skips a line when processing a TextStream file.
• Write. Places a string in the TextStream file.
• WriteBlankLines. Writes x number of newline characters to
the TextStream file.
• WriteLine. Writes a string in the TextStream file

Scripting related to File system


Working with File System
The main runtime object is the FileSystemObject from which all other runtime
objects are derived (except for the dictionary object, which is independent of
the FileSystemObject). lists of VBScript runtime objects.
FileSystemObject
Object Access Provided
Drive Disk drive properties
Drives Collection System drive information
File File properties
Files Collection All files contained in the
specified folder
Folder Folder properties
Folders Collection All folders contained in the
specified folder
To use the FileSystemObject within your VBScripts you must first establish an
instance of it. You can do this using the WScript object’s CreateObject() method and
by referencing it as Scripting. FileSystemObject. This is demonstrated in the
following example.
Set fsoObject = WScript.CreateObject ("Scripting.FileSystemObject")
Here fsoObject is just the name that I assigned to a variable that can now be used
by the rest of the script to reference the properties and methods of
the FileSystemObject. With this instance of the FileSystemObject now established the
script is read to interact with the Windows file system.Let’s put this
previous FileSystemObject example to work in a few quick examples to see how it
really works.
Displaying Drive Free Space
This first example demonstrates how to use a number of methods and properties of
the VBScript runtime objects to access drive information. Specifically the example
shown here displays the amount of free space on a computer’s C: and D: drives.
' * Script Name: Script 5.vbs *
Option Explicit
On Error Resume Next
dim fsoObject, drive1, drive2
set fsoObject = WScript.CreateObject("Scripting.FileSystemObject")
set drive1 = fsoObject.GetDrive(fsoObject.GetDriveName("c:"))
set drive2 = fsoObject.GetDrive(fsoObject.GetDriveName("d:"))

' ********* Main processing section **********


' Call a function that displays drive information
Free_Space()
' *********** Procedures go here *************
' This function displays the amount of free space on drive 1 and drive 2
Function Free_Space()
WScript.Echo( "Free Space on drive 1 is: " _
& FormatNumber(drive1.FreeSpace / 1024 , 0) & " KB")
WScript.Echo( "Free Space on drive 2 is: " _
& FormatNumber(drive2.FreeSpace / 1024 , 0) & " KB")
End Function

The script begins by defining three variables. The first variable is fsoObject. It will be
used to create an instance of the FileSystemObject as discussed earlier. The next two
variables will be used to set up references to the computer’s C: and D: drives. The
two statements that set up the values of these two variables for the computer’s
drives probably look a little complex to you at first. So let’s take a moment and
break them down. First, the GetDriveName() method of the FileSystemObject is used
by appending it to the variable fsoObject (for example, fsoObject.GetDriveName()).
Remember that the fsoObject variable provides the script with a reference to
the FileSystemObject and its properties and methods. The GetDriveName() method
returns the name of the drive associated with the specified driver letter (that
is, C: or D:).
Next, the FileSystemObject object’s GetDrive() method is used to retrieve
the Drive object associated with the specified drive name. The reason that we need
to establish a reference to the Drive object is because we are going to want to use
itsFreespace property a little later in the script. After executing the statements in the
script’s initialization section, the VBScript statement in the main processing section
executes. There is only one VBScript statement in this section and it calls a function
named Display_Msg(). The function then executes. Its job is to display the amount of
free space on each drive. This is accomplished by taking the amount of free space
left on a given drive as contained by the Drive object’s FreeSpaceproperty and
dividing it by 1024 (1 kilobyte or 1 KB). The results are then formatted using
the Driveobject’s FormatNumber() method, which in this case formats the number
with zero trailing decimal spaces (that is, as whole number).When I ran this script on
my computer, I got the following results.
C:\>CScript "Script 5.vbs"
Microsoft (R) Windows Script Host Version 5.6

Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.

Free Space on drive 1 is: 11,116 KB

Free Space on drive 2 is: 15,784 KB

C:\>
Examining File System Types

Let’s look at another example of how to work with the methods and properties of the
VBScript runtime objects. This time we’ll write a VBScript example that displays the
type of file system that the computer’s C: and D: drives have been formatted with.
' * Script Name: Script 6.vbs*

Option Explicit

On Error Resume Next

dim fsoObject, drive1, drive2

set fsoObject = WScript.CreateObject("Scripting.FileSystemObject")

set drive1 = fsoObject.GetDrive("C:")

set drive2 = fsoObject.GetDrive("D:")

' ********* Main processing section **********

' Call a function that displays drive information

Used_Disk()

' *********** Procedures go here *************

' This function displays the file system used to format drive 1 and drive 2

Function Used_Disk()

WScript.Echo("The file system used on drive 1 is: " & drive1.FileSystem)

WScript.Echo("The file system used on drive 2 is: " & drive2.FileSystem)

End Function
As you can see this VBScript is similar to the previous example. The same variables
are defined in the initialization section. In addition, the same instance of
the FileSystemObject is set up and once again its GetDrive() method is used to
retrieve Drive object references to each drive on the computer.Next, a single
VBScript statement in the main processing section calls a function that displays a file
system type for each drive.
This is accomplished by using Drive object’s FileSystemproperty.When I ran this
script on my computer I received the following results.
C:\>CScript "Script 6.vbs"
Microsoft (R) Windows Script Host Version 5.6

Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.

The file system used on drive 1 is: NTFS

The file system used on drive 2 is: NTFS

C:\>
Examining File Properties
Let’s look at one final example before we rush off and begin to master the art of
reading from and writing to text files. This example starts off like the previous two
examples by defining its variables and instantiating an instance of
the FileSystemObject. This time the FileSystemObject object’sGetFile() method is
used. This method is used to retrieve the File object associated with the specified
file, which in this example is c:\winzip.log.Again, a VBScript statement in the main
processing section calls on a function named Display_Msg(). The function contains a
number ofWScript.Echo statements each of which displays a different property
associated with the Fileobject.
' ********************************************

' * Script Name: Script 7.vbs *

' * Author: Bit*

' * Created: 03/02/08 *

' ********************************************

' **** Perform script initialization here ****

Option Explicit

On Error Resume Next

dim fsoObject, targetFile

set fsoObject = WScript.CreateObject("Scripting.FileSystemObject")

set targetFile = fsoObject.GetFile("d:\Test.vbs")

' ********* Main processing section **********

' Call a function that displays drive information

Details()

' *********** Procedures go here *************

' This function displays file properties

Function Details()

WScript.Echo("File properties of d:\Test.vbs")


WScript.Echo("-----------------------------------")

WScript.Echo("Created on: " & targetFile.DateCreated)

WScript.Echo("Last Modified: " & targetFile.DateLastModified)

WScript.Echo("Last Accessed: " & targetFile.DateLastAccessed)

WScript.Echo("File Name: " & targetFile.Name)

WScript.Echo("File Path: " & targetFile.Path)

WScript.Echo("File Type: " & targetFile.Type)

WScript.Echo("File Size: " & targetFile.Size)

End Function
The following output was displayed when I ran this script.
C:\>CScript "Script 7.vbs"

Microsoft (R) Windows Script Host Version 5.6

Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.

File properties of d:\Test.vbs

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

Created on: 2/4/2008 11:23:36 PM

Last Modified: 2/4/2008 10:38:52 AM

Last Accessed: 2/4/2008

File Name: Test.vbs

File Path: D:\Test.vbs

File Type: VBScript Script File

File Size: 1081

C:\>
Creating Documents, Reports, and LogsBy this point you should have a fairly good
understanding of what the VBScript runtime objects are and what they can do. Now
let’s look at how you can use them to generate reports, logs, and other types of text
documents.To work with files and their contents you must first establish an instance
of the FileSystemObject within your VBScript as shown here.
set fsoObject = WScript.CreateObject("Scripting.FileSystemObject")
Next, you should always check to see if the file that you want to work with already
exists. If it does, you can open it. If it does not already exist, you can create it and
then open it. You can check to see if a file exists using
the FileSystemObject object’s FileExists property as shown here.
If (fsoObject.FileExists("C:\displayText.txt" ) ) Then
You must open a file before you can work with it. You can use
the FileSystemObject object’sOpenTextFile() method to open files. To use this
method you need to supply a few pieces of information including the following.
• The name and path of the file to be opened
• Whether you want the file to be opened for reading, writing, or
appending
• Whether to create the file if it does not existTable defines constants
that are used to tell the OpenTextFile() method what you want to do
once the file is opened.
OpenTextFile() Constants
Constant Description Value
ForReading Opens a file for reading 1
ForWriting Opens a file for writing 2
ForAppending Opens a file for 8
appending
Table defines two options that govern what the OpenTextFile() method should do
when the file to be opened does and does not exist.
Table : OpenTextFile() File Creation Options
Value Description
True Open the file if it exists,
otherwise create and open it
False Open the file if it exists,
otherwise do not create it
Opening and Closing Files
It is very important that you correctly specify the type of operation that you are
opening a file for (reading, writing, or appending). If you open a file to write to it and
the file exists, then the file will be reinitialized. In other words, any data that is
already in the file is lost and the file pointer is placed at the beginning of the new file
(in the first row and column of the file).By appending to a file, you are able to
preserve its contents and add to it. In other words, the file is opened and the file
pointer is placed at the end of the file in the last row and column position.The file
pointer is used to identify where the next character of data will be placed with a file.
In a newly initialized file, the pointer would automatically be positioned in the upper-
left corner (row 0, column 0). If one new character of information were added, the
pointer would be moved over one position to column 1 in row 0. If a carriage return
were added (indicating an end-of-line marker), then the file pointer would move to
column 0 row 1. Knowing the location of the file pointer and how it is moved around
is important, especially if you will be writing to or reading from files that have fixed
record formats with data fields starting and ending in specified column
positions. Okay, enough about the file pointer. Let’s look at an example that ties
together everything that we have talked about. In this example, I’ve written a
VBScript that opens a file named myFile.txt, which resides in the root directory of
myC: drive. If the file already exists, then the script opens it but if it does not
already exist it will be created and opened.
' * Script Name: Script 8.vbs *

Option Explicit

On Error Resume Next


Dim fsoObject, open_File, target_File

Set fsoObject = WScript.CreateObject("Scripting.FileSystemObject")

target_File = "D:\ displayText.txt"

' ********* Main processing section **********

' Call a function that displays drive information

Open_File()

open_File.WriteLine "This line of data should be written to the text file."

Close_File()

' *********** Procedures go here *************

' This function opens a file

Function Open_File()

If (fsoObject.FileExists(target_File ) ) Then

Set open_File = fsoObject.OpenTextFile(target_File, 8 )

Else

Set open_File = fsoObject.OpenTextFile(target_File, 2, "True" )

End If

End Function

' This function closes a file

Function Close_File()

open_File.Close()

End Function
The file is opened using the forWriting constant ( with a value of 2 ) if it already
exists. If the file does not exist, then the forAppending constant (with a value of 8 )
is specified to open the file and place the file pointer at the end of the file.If you take
at look at the script’s main processing section you will see the following statement
between a pair of function calls, which open and close the file.
open_File.WriteLine "This line of data should be written to the text file."
This statement writes one line of data to the file and executes a carriage return
placing the file pointer in the first column of the following line. I’ll talk more about
the use of this and other methods that are used to write data to files in just a
bit. The last statement in the main processing section calls a function that executes
the following statement.
open_File.Close()
This statement executed the FileSystemObject object’s close() method i to close the
opened file. You must remember to close any file that you open before allowing your
script to end. Failing to do so may cause an error the next time that you open the file
because the end-of-file marker will not have been created.Run this script and open
the myFile.txt file and you’ll see the following line of data.
This line of data should be written to the text file.
Writing to Files

As you just learned, you should always check for the existence of a file before
creating it. Once opened, you have several different ways in which you can write text
data to your files.One option is to write a specific number of characters at a time.
This technique is best used when you need to write carefully formatted data to your
files such as when you write reports with data that appears in columns. Another
option for writing to a file is to write an entire line of data at a time. This technique is
best used when your documents are more free-formed and is probably the option
that you’ll use most often, especially if you plan to create log files in which you
record error messages and other types of event information as your scripts
execute.Finally, you might want to add blank lines to your files. Blank lines are
especially useful for formatting your documents to improve their presentation and
make them easier to read.
Adding Characters to a File
You can write a specific number of characters to a file at a time using
the FileSystemObject object’sWrite() method. This method does not automatically
append a carriage return at the end of each write operation. Therefore, the next time
a write operation occurs additional text is inserted immediately following the text
written by the previous write operation.The following example demonstrates how you
can use the Write() method to append text to an existing file.
Set fsoObject = WScript.CreateObject("Scripting.FileSystemObject")

Set open_file = fsoObject.OpenTextFile("d:\ displayText.txt", 8 )

open_file.Write("Welcome to ")

open_file.Write("KR Testing Solutions!")

open_file.Close()
As you can see even though two separate write operations occurred, the text for
both write operations was placed on the same line.
Adding a Line to a File
By replacing the Write() method with
the FileSystemObject object’s WriteLine() method in the previous example, you can
change the previous script to write data to the file a line at a time.
Set fsoObject = WScript.CreateObject("Scripting.FileSystemObject")

Set open_file = fsoObject.OpenTextFile("d:\ displayText.txt", 8 )

open_file.WriteLine("Welcome to KR Testing Solutions!")

open_file.Close()
The WriteLine() method automatically adds a carriage return to the end of each line
returning the file pointer to the first column of the next line.
Adding Blank Lines to a File
If you want to format your text files with blank lines to create better looking reports
or make them easier to read you can use
the FileSystemObject object’s WriteBlankLines() method. When executed, this
method writes a blank line to the file and executes a carriage return.The following
example demonstrates how to use the WriteBlankLines() method to format the data
in a small report.
Set fsoObject = WScript.CreateObject("Scripting.FileSystemObject")
Set myCDrive = fsoObject.GetDrive("d:")

Set open_file = fsoObject.OpenTextFile("d:\ displayText.txt", 8 )

open_file.WriteLine("------------------------------")

open_file.WriteBlankLines(1)

open_file.WriteLine(" My d: Drive Report ")

open_file.WriteBlankLines(1)

open_file.WriteLine("------------------------------")

open_file.WriteBlankLines(2)

open_file.WriteLine("File System - " & myCDrive.FileSystem)

open_file.WriteLine("Total Size - " & myCDrive.TotalSize)

open_file.WriteLine("Free Space - " & myCDrive.AvailableSpace)

open_file.Close()Reading from Files


Reading the contents of a file is handled in much the same way as writing to it. First,
be sure that the file exists. If it does, then your script may open it. The next thing
your script should do is use the TextStream object’s AtEndOfStream property to find
out if the file has any data in it. After all, there is no point to trying to read an empty
file. In fact, you should check the value of theAtEndOfStream property just before
each read operation to be sure that your script has not reached the end of file
marker (e.g., the end of the file). The first thing that you need to do to begin reading
a text file is create an instance of the FileSystemObject and then use
theFileSystemObject object’s OpenTextFile() method as shown here.
Set fsoObject = CreateObject("Scripting.FileSystemObject")

Set open_file = fsoObject.OpenTextFile("d:\ displayText.txt", 1 )


As you can see the forReading constant has been specified. Next you could set up a
loop that runs until the AtEndOfStream property has a value of true (the end of the
file is reached). During each iteration of the loop your script should read a line of text
using the FileSystemObject object’sReadLine() method as shown here.
Do while False = open_file.AtEndOfStream

WScript.Echo(open_file.ReadLine())

Loop

The preceding VBScript statements will process every line in the file, terminating
when the end of file marker is reached. After your script is done reading the file, it
can close it as shown here.
open_file.Close
If you put these lines of code together and ran them as a script using the CScript
execution host you’d see output similar to the following.
C:\>CScript test.vbs
Microsoft (R) Windows Script Host Version 5.6

Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.

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

My d: Drive Report

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

File System - NTFS

Total Size - 2146631554

Free Space - 234554452

C:\>

In this example we read an entire file by reading it one line at a time. There are a
number of other techniques for reading files. These include
• Skipping lines when reading a file
• Reading a specified number of characters from a file
• Reading an entire file in one operation
Skipping Portions of a File
If a file has headers or other information that you are not interested in reading you
can always skip them and read only the portion of the file that interests you. For
example, the file that we have been working with contains a five-line header followed
by two blank lines after which the data in the report begins.You can use either of the
following methods, both of which belong to theFileSystemObject, to skip text in a
file.
• Skip(). Skip a specific number of characters
• SkipLine(). Skips a lineThe Skip() method lets you supply a number
indicating how many characters should be skipped.
For example, the following statement would skip 25 characters in a file referenced
as open_file.
open_file.Skip(25)
Unfortunately, the SkipLine() method does not allow you to pass it a number,
indicating how many lines to skip. If you want to skip more than one line, you can
wrap the method up inside a loop as demonstrated here.
For i = 1 to 7open_file.SkipLine()Next
Here the first seven lines of the file referenced as open_file would be skipped.
Reading Formatted Data
If your file has been formatted to contain fixed length data, then you have the option
of reading it by character instead of by line. To do so you will use
the FileSystemObject object’s Read()method.The following example demonstrates
how to use this method. Here a reference is set up for a file named myfile.txt. Then
a For loop is set up to skip the first seven lines of the file using
theSkipLine() method. Next the Skip() method is used to skip the first fourteen
characters on the eighth line. Finally the next four characters, beginning with the
twenty-third character are read and then displayed. Then the file is closed.
Set fsoObject = CreateObject("Scripting.FileSystemObject")
Set open_file = fsoObject.OpenTextFile("d:\ displayText.txt", 1 )

For i = 1 to 7

open_file.SkipLine()

Next

open_file.Skip(14)

WScript.Echo("The file system in use on this drive is: "

& open_file.Read(4))open_file.Close

Reading Entire Files


Another way in which you can read files is to read the entire file all at once using
theFileSystemObject object’s ReadAll() method as demonstrated in the following
example.
Set fsoObject = CreateObject("Scripting.FileSystemObject")

Set open_file = fsoObject.OpenTextFile("d:\ displayText.txt", 1 )

read_rpt = open_file.ReadAll()open_file.Close()MsgBox(read_rpt)
In this example, the entire file is read using a single statement, which assigns the
data read by theReadAll() method to a variable named read_rpt. The file is then
closed and the value of read_rptdisplayed using the VBScript MsgBox() function.
Performing File and Folder Administration
Managing your files and folders can involve a lot of work. Using VBScript and the
WSH you can automate much of this work. For example, typical file and folder tasks
involve copying or moving files and folders from one location to another in order to
create backups or better organize them. Administration may also include deleting
files once they have been processed or after they have reached a certain age.You
can use methods belonging to the FileSystemObject to manage one or more files or
folders at a time. FileSystemObject methods for handling files include
• CopyFile(). Copies one or more files.
• MoveFile(). Moves one or more files to a different location.
• DeleteFile(). Delete one or more files.
• FileExists(). Provides verification of whether a file contains data.
The FileSystemObject also provides a number of methods that you
can use to manage Windows folders, including
• CopyFolder(). Copies one or more folders.
• MoveFolder(). Moves one or more folders to a different location.
• DeleteFolder(). Deletes one or more folders.
• FolderExists(). Provides verification of whether a folder exists.
• CreateFolder(). Creates a new folder.Alternatively, you can also use
the File and Folderobjects to manage your files and folders instead of
the FileSystemObject. These two objects share many of the same
methods, including
• Copy(). Copies a file or folder to the specified location.
• Delete(). Removes the specified file or folder.
• Move(). Moves a file or folder to the specified location.
FileSystemObject
Managing Files and Folders
As you have already seen this afternoon the FileSystemObject is actually fairly easy
to work with. All that you have to do is establish an instance of it and you can start
using its properties and methods. In the sections that follow you’ll see examples of
how to use this object to create, copy, move, and delete files and folders.
Copying Files
Using the FileSystemObject object’s CopyFile() method you can copy one or more
files. For example, you might want to copy all the files in the folder on your
computer to a network drive at the end of each day. I’ll show you how to work with
network drives this evening. For now let’s just focus on how the CopyFile() method
works.The first step in copying a file is to set up an instance of theFileSystemObject.
Then you can execute its CopyFile() method as shown here.
Set fsoObject = CreateObject("Scripting.FileSystemObject")
fsoObject.CopyFile("d:\ displayText.txt", "d:\myDocs\ displayText.txt")
In this example, a file named myFile.txt is copied from the root folder on the C: drive
to a folder named myDocs located on the computer’s D: drive. You can modify this
example to copy more than one file using wildcard characters as shown in the next
example. Here all files in the root directly with a filename of myFile are copied to the
destination folder regardless of their file extension.
Set fsoObject = CreateObject("Scripting.FileSystemObject")
fsoObject.CopyFile("d:\ displayText.*", "d:\Docs")
Moving Files
Moving files is similar to copying them except that instead of leaving the original file
in place and placing a duplicate copy in the destination location, the original file is
moved leaving only one copy of the file. You can move one or more files using
the FileSystemObject object’s MoveFile()method.For example, you can move all files
with a .txt file extension found in the root of the C:drive to a myDocs folder on
the D: drive using the following VBScript statements.
Set fsoObject = CreateObject("Scripting.FileSystemObject")
fsoObject.MoveFile("c:\*.txt", "c:\Docs")
Deleting Files
You can use the FileSystemObject object’s DeleteFile() method to delete one or more
files. For example, you might want to write a script that cleans out a folder at the
end of each day or that deletes files after reading and processing them. You can
delete one or more files as demonstrated here.
Set fsoObject = CreateObject("Scripting.FileSystemObject")
fsoObject.DeleteFile("d:\*.txt")
Here all files that have a .txt file extension located in the root of the C: drive will be
deleted.
Creating a Folder
Working with folders is similar to working with files. You can use the FolderExists()
method of theFileSystemObject to determine if a folder exists. If the folder does not
exist, you can create it using the FileSystemObject object’s CreateFolder() method as
demonstrated here.
Set fsoObject = CreateObject("Scripting.FileSystemObject")
If (fsoObject.FolderExists("d:\Docs") = false) Then
Set myFolder = fsoObject.CreateFolder("d:\Docs")
End If
The first thing that this example does is check to see if a folder
named myDocs already exists on the computer’s D: drive. If it does not exist, then
the folder is created. Otherwise nothing happens.
Copying Folders
Copying a folder is pretty much the same as copying a file. The folder and all its
contents are copied to a new location leaving the original copy still in place. You can
copy folders using theFileSystemObject object’s CopyFolder() method.Take a look at
the following example. It copies a folder named myDocs located on the
computer’s D: drive to its C: drive.
Set fsoObject = CreateObject("Scripting.FileSystemObject")
fsoObject.CopyFolder("c:\Docs", "d:\Docs")
As you can see the CopyFolder() methods requires two arguments, the source and
destination folder names, including their complete paths. By changing the name
assigned to the destination folder, you can rename the folder as part of the copy
operation as demonstrated here.
Set fsoObject = CreateObject("Scripting.FileSystemObject")
fsoObject.CopyFolder("c:\Docs", "d:\NewDocs")
If the destination folder already exists, then the contents of the source folder are
copied into it alongside its current contents. The CopyFolder() method supports an
additional third parameter that allows you to tell it what to do if the destination
folder contains files with duplicate filenames of those found in the source folder. This
parameter is set to either a value of true or false. Setting it to true causes any
matching files to be overridden. Setting it to false prevents this from happening.
Let’s look at a couple examples. The first example prevents files with duplicate
filenames from being overridden.
Set fsoObject = CreateObject("Scripting.FileSystemObject")
fsoObject.CopyFolder("c:\Docs", "d:\Docs", "False")
The second example allows files with duplicate names to be overridden in the
destination folder.
Set fsoObject = CreateObject("Scripting.FileSystemObject")
fsoObject.CopyFolder("c:\Docs", "d:\Docs", "True")
Moving Folders
Moving a folder works pretty much the same as copying one except that moving the
folder leaves you with only the one copy. You can move folders using
the FileSystemObject object’s MoveFolder()method. This method moves a folder and
all its contents, including subfolders, to a new destination.For example, the following
VBScript statements move a folder called myDocs from the computer’s D: drive to
its C: drive.
Set fsoObject = CreateObject("Scripting.FileSystemObject")
fsoObject.MoveFolder("c:\Docs", "d:\Docs")
If a folder with the same name already exists at the root of the computer’s D: drive,
then the contents of the source folder will be copied into the existing destination
along side its current contents.
Deleting Folders
You can delete one or more folders using
the FileSystemObject object’s DeleteFolder() method. This method deletes a folder
and all its contents, including subfolders. For example, the following VBScript
statements can be used to delete a folder named myDocs located on a
computer’s D:drive.
Set fsoObject = CreateObject("Scripting.FileSystemObject")
fsoObject.DeleteFolder("d:\Docs")
Managing Files with the File Object
The File Object allows you to work with one file at a time as opposed to
the FileSystemObject, which lets you manage multiple files. Using the File object
instead of the FileSystemObject requires a little more work. You still have to create
an instance of the FileSystemObject to interact with the file system. You also need to
use the FileSystemObject object’s GetFile() method to retrieve a Fileobject that
represents the file that your script will be managing. Once these two things are set
up you can execute any of the File object’s methods.
Copying a File
Using the File object’s Copy() method you can copy a file from one location to
another. This method does not support the use of wildcard characters and cannot
therefore be used to copy multiple files.The following example demonstrates how to
use the File object’s Copy() method to copy a file named myFile.txt from
the myDocs folder on the computer’s D: drive to the root of the C: drive.
Set fsoObject = CreateObject("Scripting.FileSystemObject")
Set source_file = fsoObject.GetFile("c:\Docs\ displayText.txt")
source_file.Copy("d:\")
In this example, the FileSystemObject object’s GetFile() method is used to establish
a reference to the file that is to be copied. Then the Copy() method is used to set the
destination where the file is to be copied.
Moving a File
As you probably expect by now, moving a file using the File object’s Move() method
works almost exactly like copying it using the Copy() method. For example, the
following VBScript statements demonstrate how to move a file from one location to
another.
Set fsoObject = CreateObject("Scripting.FileSystemObject")
Set source_file = fsoObject.GetFile("c:\Docs\ displayText.txt")
source_file.Move("d:\")
Deleting a File
You can delete an individual file using the File Object’s Delete() method. Like
the File object’s other methods, the Delete() method does not support wildcard
characters limiting it to being able to delete just one file at a time.Take a look at the
following example. Here a file named myFile.txt is deleted from a folder
named myDocs located on the computer’s D: drive.
Set fsoObject = CreateObject("Scripting.FileSystemObject")
Set source_file = fsoObject.GetFile("c:\Docs\ displayText.txt ")
source_file.Delete()
Managing Folders with the Folder Object
The Folder object is similar to the File object only it works with one folder at a time
instead of one file at a time. Like the File object, it requires a little more work to set
up than does simply using theFileSystemObject. First, you’ll need to instantiate
the FileSystemObject.
Then you must use theFileSystemObject object’s GetFolder() method to retrieve
a Folder object that represents the folder that your script will be working with. Once
these two things are set up you can execute any of theFolder object’s methods.
Copying a Folder
Like the File object, the Folder object supports the Copy() method. Because it
doesn’t support wildcard characters it is useful only when you want to work with a
single folder at a time. TheCopy() method copies the folder and all its contents,
including any subfolders, to a new location.For example, the following VBScript
statements demonstrate how to use the Copy() method. In this case a folder
named myDocs is copied from the root of the computer’s D: drive to the root of the
computer’s C: drive.
Set fsoObject = CreateObject("Scripting.FileSystemObject")
Set source_folder = fsoObject.GetFolder("d:\Docs")
source_folder.Copy("c:\")
Moving a Folder
The Folder object’s Move() method lets you move a folder from one location to
another. This method recursively copies a folder and all its contents. Because it does
not support wildcard characters, this method can only move one folder at a time, as
opposed to the FileSystemObjectobject’s MoveFolder() method, which can move any
number of folders in a single operation.The following example demonstrates how to
use this method to move a folder. In this case the folder is named myDocs and it is
moved from the computer’s D: drive to its C: drive.
Set fsoObject = CreateObject("Scripting.FileSystemObject")
Set source_folder = fsoObject.GetFolder("d:\Docs")
source_folder.Move("c:\")
Deleting a Folder
You can delete a folder using the Folder object’s Delete() method. Wildcard character
matching is not supported so it only works with one folder at a time.
If you need to delete more than one folder you can use
he FileSystemObject object’s DeleteFolder() method, discussed earlier in this
chapter.This method deletes the specified folder and all its contents, including
subfolders.
Its use is demonstrated here.
Set fsoObject = CreateObject("Scripting.FileSystemObject")
Set source_folder = fsoObject.GetFolder("d:\Docs")
source_folder.Delete()

QTP Scripts examples

1. Script for sending a mail using outlook express.


Dim objOutlookMsg,objOutlook
Set objOutlook = CreateObject(“Outlook.Application”)
Set objOutlookMsg = objOutlook.CreateItem(olMailItem)
objOutlookMsg.To = ““
objOutlookMsg.CC = “ “
objOutlookMsg.BCC = ““
objOutlookMsg.Subject = “test”
objOutlookMsg.Body = ““
objOutlookMsg.Attachments.Add “C:\Documents and Settings\Desktop\testreport.txt”
objOutlookMsg.Send
2. Script for opening a Notepad file.
In Expert view write a builtin funtion
invokeapplication”c:/whatever the path”
Run

Dim a
Set a = WScript.CreateObject (“WSCript.shell”)
a.run “notepad.exe”
Dim oShell
Set oShell = CreateObject (“WSCript.shell”)
oShell.run “cmd/notepad.exe”
Set oShell = Nothing
DsystemUtil.Run “Notepad.exe”
3. Script for connecting the oracle database
public void connectDB()
{
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adUseClient = 3
Set objCon=CreateObject(“ADODB.Connection”)
Set objRec=CreateObject(“ ADODB.Recordset”)
objCon.Open “DRIVER={Oracle in
OraHome92};SERVER={Servername};UID={Username};PWD={Password};DBQ={Dbnmae}”
objRec.CursorLocation = adUseClient
objRec.Open “Select {Col name} from tablename”,objCon,adOpenStatic,adLockOptimistic
While(objRec.EOF)
objRec.MoveNext
Msgbox ”Result” & objRec.Fields.Item(“{Col name}”)& vbCrLf
Wend
objRec.Close
objCon.Close
Set objRec=Nothing
Set objCon=Nothing
Msgbox “Executed Sucessfully”
}
Use code only that which is inside the function connectDB
4. Two ways to connect QC with QTP.
Connect manually
1. To connect to TD from QTP follow the steps…
2. Open Qtp ==> Tools ==>
3. Select TestDirector Connection ==>
4. In Server Connction Box Enter TD address(URL of TD) ==>
5. Click Connect==>
6. In project Connection Box Enter the Details Domain,Project,User name and Password ==>
7. Click Connect If you want to reconnect on startup check the reconnect on startup and save
password for reconnection on startup.
8. Then close.
Using Script
Set qtApp = CreateObject(“QuickTest.Application”)
qtApp.Launch
qtApp.Visible = True
qtApp.TDConnection. Connect “URL”, “DOMAIN”, “PROJECT”, “USERNAME”,
“PASSWORD”, False
5. Retrieve Data from Excel sheet
Dim FilePath, Excelone,ExcelSheet,Val
Set FilePath= CreateObject(“srcfilepath”)
Set ExcelSheet = FilePath.GetSheet(sheetid)
Set Val= ExcelSheet.ActiveSheet.Cells(1,1).value

‘Below script for creating an excel sheet with values 1,2,3


Dim Excel,ExcelSheet
Set Excelone=CreateObject(“Excel.Application”)
Set ExcelSheet=CreateObject(“Excel.Sheet”)
ExcelSheet.Application.visible=true
ExcelSheet.ActiveSheet.Cells(1,1).value=1
ExcelSheet.ActiveSheet.Cells(1,2).value=2
ExcelSheet.ActiveSheet.Cells(1,3).value=3
Excelone.Saveas “E:\tests.xls”
Excelone.quit
Set ExcelSheet=Nothing

6. Some more stuff related to QTP Script.


Set Word = CreateObject(“Word.Application”)
oWord.DisplayAlerts = False
oWord.Visible = False
oWord.documents.open “testWordDoc.doc”
Set Doc = oWord.ActiveDocument
Set Range = oDoc.content
oRange.ParagraphFormat.Alignment = 0
oRange.insertafter vbcrlf ‘& “ “ & vbcrlf
oRange.collapse(0)
oRange.InlineShapes.AddPicture “ImagePath.bmp”, False, True
oWord.ActiveDocument.Save
oWord.Application.Quit True
Set Range = Nothing
Set Doc = Nothing
Set Word = Nothing
‘————————————————————–
Cmd.activeconnection=“Provider=SQLOLEDB.1;Password=;Persist Security Info=True;User
ID=sa;Initial Catalog=pubs;
Dim res,cmd,sql
Set Res=createobject(“adodb.recordset”)
Set Cmd=createobject(“adodb.command”)
Cmd.activeconnection=“Provider=SQLOLEDB.1;Password=;Persist Security Info=True;User
ID=sa;Initial Catalog=pubs;Data Source=192.168.0.69″
Cmd.CommandType = 1
sql=“select emp_id,fname from dbo.employee”
Cmd.CommandText = sql
Set res = Cmd.Execute()
i=1
While not res.eof
logid = res(“emp_id”).value
logname=res(“fname”).value
print logid
print logname
i=i+1
res.movenext
wend
Set res = nothing
Set cmd.ActiveConnection = nothing
Set Cmd= nothing
‘————————————————————–
Set ExcelObj = CreateObject(“Excel.Application”)
aatype=“F:\templet.xls”
ExcelObj.Workbooks.Open(aatype)
Set NewSheet = ExcelObj.Sheets.Item(2)
Dim rs,sq,pkey
set conn=createobject(“adodb.connection”)
set rs=createobject(“adodb.recordset”)
set rs1=createobject(“adodb.recordset”)
conn.open= “Provider=OraOLEDB.Oracle.1;Password=*;Persist Security Info=True;User
ID=*;SERVER=*;Data Source=*;DBQ=*;”
sql=“select * from table”
rs.open sql,conn
i=1
do while not rs.eof
values1=rs(“pkey”)
values2=rs(“name”)
NewSheet.Cells(i+1,1).Value =values1
NewSheet.Cells(i+1,2).Value =values2
i=i+1
rs.movenext
Loop
‘————————————————————–
ExcelObj.ActiveWorkbook.Saveas “F:\data.xls”
ExcelObj.Quit
Set ExcelObj = Nothing
rs.close
set rs=nothing
conn.close
set conn=nothing
‘————————————————————–
Dim Excel,ExcelSheet
Set Excelone=CreateObject(“Excel.Application”)
Set ExcelSheet=CreateObject(“Excel.Sheet”)
ExcelSheet.Application.visible=true
ExcelSheet.ActiveSheet.Cells(1,1).value=1
ExcelSheet.ActiveSheet.Cells(1,2).value=2
ExcelSheet.ActiveSheet.Cells(1,3).value=3
Excelone.Saveas “E:\tests.xls”
Excelone.quit
Set ExcelSheet=Nothing
‘————————————————————–
Set fs=CreateObject(“excel.application”)
fs.Visible=True
Set excelbook=fs.Workbooks.Add
Set excelsheet=excelbook.worksheets(1)
excelsheet.cells(1,1)=“??”
excelsheet.saveas “e:\1.xls”
excelsheet.application.quit
fs.Quit
‘————————————————————–
set fs=createobject(“excel.application”)
fs.visible=true
set excbook=fs.workbooks.open(“f:\1.xls”)
set excsheet=excbook.worksheet(1)
excsheet.cells(1,1).value=“Test”
excbook.save
fs.quit
‘————————————————————–
Dim qtApp ,pDefColl,pDef ,rtParams,rtParam
Set qtApp = CreateObject(“QuickTest.Application”)
qtApp.Launch
qtApp.Visible = True
qtApp.Open “C:\Test1″
Set pDefColl = qtApp.Test.ParameterDefinitions
cnt = pDefColl.Count
Indx = 1
While Indx <= cnt
Set pDef = pDefColl.Item(Indx)
Indx = Indx + 1
Wend
Set rtParams = pDefColl.GetParameters()
Set rtParam = rtParams.Item(“InParam1″)
rtParam.Value = “songfun”
qtApp.Test.Run , True, rtParams
MsgBox rtParams.Item(“OutParam1″).Value
‘————————————————————–
Dim a,b,c
Set a = createobject(“excel.application”)
a.visible = true
Set b = a.workbooks.add
Set c = b.worksheets(1)
c.cells(1,1) = “1″
c.cells(1,2) = “2″
c.cells(1,3) = “3″
c.saveas “e:\testtwo.xls”
c.application.quit
a.quit
‘————————————————————–
set fs=createobject(“excel.application”)
fs.visible=true
set excbook=fs.workbooks.open(“f:\1.xls”)
set excsheet=excbook.worksheet(1)
excsheet.cells(1,1).value=“Test1″
excbook.save
fs.quit
‘————————————————————–
Set alapp=createobject(“Excel.Application”)
alapp.application.visible=true
Set xlbook=alapp.workbooks.open(“e:\test.xls”)
Set xlSheet = xlBook.Worksheets(“Sheet1″)
count1=datatable.GetSheet(“Action1″).getrowcount
For i=1 to count1
alapp.cells(i,1)= datatable.GetSheet(“Action1″).getparameter(“Test1″).valuebyrow(i)
Next
xlSheet.saveas “e:\1.xls”
alapp.quit
Set excel=nothing

Query Forum
How to capture tool tip in QTP?
E.g.: On Amazon.com, when you bring the mouse over the ‘A9′ search image (on the
top-left side of the page), it shows ‘A9 search’ as tool-tip. This can be captured using
following code:
strToolTip=Browser(“title:=Amazon.*”).Page(“title:=Amazon.*”).Image(“src:=.*a9search.*”).getRO
Property(“alt”)
msgbox strToolTip
How to Maximising a Browser?
Sub MaxBrowser( ByRef Browser )
hwnd= Browser.GetROProperty(“hWnd”)
Window(“hWnd:=“&hwnd).Maximize
End SubCall MaxBrowser(Browser(“micClass:=Browser”))
How to extract column from webpage ?
Dim colA(),colB()
totalRows = Browser(“<yourBrowser>“).Page(“<yourPage>“).WebTable(“<yourtable>“).RowCount
ReDim colA(totalRows), colB(totalRows)
For x = 1 to totalRows
colA(x) =
Browser(“<yourBrowser>“).Page(“<yourPage>“).WebTable(“<yourtable>“).GetCellData(x,<firstcol
umn>)
colB(x) =
Browser(“<yourBrowser>“).Page(“<yourPage>“).WebTable(“<yourtable>“).GetCellData(x,<second
column>)
Next
How to Capture Screen shot ?
Sub captureScreenShot ()
strStoreSnapshotMode = Setting(“SnapshotReportMode”)
Setting(“SnapshotReportMode”) = 0
Browser(“name:=.*”).Page(“title:=.*”).Sync
Setting(“SnapshotReportMode”) = strStoreSnapshotMode
End Sub
How to Call SQL stored procedure from QTP?
Function RunStoredProcedure(StoredProcedureName)
sDatabaseName=“ABC”
sUID=“xyz”
sPWD=“ABC_xyz” ‘ Create the database object
Set cm = CreateObject(“ADODB.Command”)
‘ Activate the connection.
cm.ActiveConnection = “DRIVER={Microsoft ODBC for Oracle}; “ &_
“SERVER=“ & sDatabaseName & “;User ID=“ & sUID & “;Password=“ & sPWD & “ ;”
‘ Set the command type to Stored Procedures
cm.CommandType = 4
‘ Stored Procedures
cm.CommandText = StoredProcedureName
‘ Define Parameters for the stored procedure
cm.Parameters.Refresh
‘ Pass input value. Assuming Stored Procedure requires 2 parameters
cm.Parameters(0).Value = “Kuldeep”
cm.Parameters(1).Value = “Kumar”
‘ Execute the stored procedure
cm.Execute()
Set cm = Nothing
End Function
How to write the test Result (Output) on Excel sheet?
Dim objexcel
Set objexcel= CreateObject(“Excel.sheet”)
objexcel.Visible = True
objexcel.Workbooks.add
With Window(“Calculator”)
.WinButton(“5″).Click
.WinButton(“*”).Click
.WinButton(“3″).Click
.WinButton(“=“).Click
End With
result= Window(“Calculator”).WinEdit(“Edit”).GetROProperty(“text”)

If result=15 Then
objexcel.ActiveSheet.Cells(1,1).Value = “test is pass”
Reporter.ReportEvent micPass,”Calculation”, result
Else
objexcel.ActiveSheet.Cells(1,1).Value = “test is Fail”
Reporter.ReportEvent micFail,”Calculation”, “Expected Result is 15” +”Acutal is “+result
End If
What is the use of function GetROProperty()?
GetROProperty is used to retrieve properties listed in Object Spy.
Example: hWnd=Browser(“browser_name”).GetROProperty(“hwnd”)
Window(“hwnd:=“ & hWnd).Minimize

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