Академический Документы
Профессиональный Документы
Культура Документы
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
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
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.
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>
VBScript Variables
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:
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
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".
<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>
Sub cmdCalculate_OnClick
Dim AmountofTax
Dim CRLF
Dim Message
Dim Subtotal
Dim TABSPACE
Dim TAX_RATE
Dim TotalCost
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)
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)
Alternatively, you can substitute the single quotation mark (‘) character for the
Rem keyword as shown below.
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:
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
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).
<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)
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.
<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
AreaCode = CInt(txtAreaCode.Value)
End Select
MsgBox "The closest dealership to you is in " & DealerLocation
End Sub
-->
</SCRIPT>
</BODY>
</HTML>
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
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
Count = 0
End Sub
-->
</SCRIPT>
Exit a For...Next
You can exit a For...Next statement with the Exit For keyword.
Dim Count
Dim Scores(10)
Count = 0
Sub cmdNext_OnClick()
Dim Score
Dim i
Score = CSng(txtScore.Value)
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
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
For i = 0 to Count-1
Sum = Sum + Scores(i)
Next
Count = 0
End Sub
-->
</SCRIPT>
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
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.
Sub cmdGetScores_OnClick()
Dim Count
Dim Scores(10)
Dim Score
Dim Average
Dim Sum
Dim i
Score = 0
For i = 0 to Count-1
Sum = Sum + Scores(i)
Next
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
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!
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
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
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
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
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
Used_Disk()
' This function displays the file system used to format drive 1 and drive 2
Function Used_Disk()
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
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.
' ********************************************
' ********************************************
Option Explicit
Details()
Function Details()
End Function
The following output was displayed when I ran this script.
C:\>CScript "Script 7.vbs"
-----------------------------------
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
Open_File()
Close_File()
Function Open_File()
If (fsoObject.FileExists(target_File ) ) Then
Else
End If
End Function
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")
open_file.Write("Welcome to ")
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")
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:")
open_file.WriteLine("------------------------------")
open_file.WriteBlankLines(1)
open_file.WriteBlankLines(1)
open_file.WriteLine("------------------------------")
open_file.WriteBlankLines(2)
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
------------------------------
My d: Drive Report
------------------------------
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)
& open_file.Read(4))open_file.Close
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()
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
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