• No results found

Vb Script_Good One

N/A
N/A
Protected

Academic year: 2021

Share "Vb Script_Good One"

Copied!
13
0
0

Loading.... (view fulltext now)

Full text

(1)

VBScript Data Types VBScript Data Types

VBScript has only one data type called a Variant. A Variant is a special kind of data type that VBScript has only one data type called a Variant. A Variant is a special kind of data type that can contain different kinds of information, depending on how it

can contain different kinds of information, depending on how it is used. Because Variant is the onlyis used. Because Variant is the only data type in VBScript, it is

data type in VBScript, it is also the data type returned by all also the data type returned by all functions in VBScript.functions in VBScript.

At its simplest, a Variant can contain either numeric or string information. A Variant behaves At its simplest, a Variant can contain either numeric or string information. A Variant behaves as a number when you use it

as a number when you use it in a numeric context and as in a numeric context and as a string when you use it a string when you use it in a string context.in a string context. That is, if you are

That is, if you are working with data that looks like numbers, VBScript assumes that it is working with data that looks like numbers, VBScript assumes that it is numbers andnumbers and does what is most appropriate for numbers. Similarly, if you're working with data that can only be does what is most appropriate for numbers. Similarly, if you're working with data that can only be string data, VBScript treats it as string data. You can always make numbers behave as strings by string data, VBScript treats it as string data. You can always make numbers behave as strings by enclosing them in quotation marks (" ").

enclosing them in quotation marks (" ").

You can also declare a variable implicitly by simply using its name in your script. That is not You can also declare a variable implicitly by simply using its name in your script. That is not generally a good practice because you could misspell the variable name in one or

generally a good practice because you could misspell the variable name in one or more places, causingmore places, causing unexpected results when your script is run. For that reason, the

unexpected results when your script is run. For that reason, the Option ExplicitOption Explicitstatement is statement is availableavailable to

to requrequire ire expliexplicit declaracit declaration of tion of all all varivariablesables. . The Option Explicit stateThe Option Explicit statement should be ment should be the firstthe first statement in your script.

statement in your script.

Looping allows you to run a group of statements repeatedly. Some loops repeat statements Looping allows you to run a group of statements repeatedly. Some loops repeat statements until a condition is False; others repeat statements until a condition is True. There are also loops that until a condition is False; others repeat statements until a condition is True. There are also loops that repeat statements a specific number of times.

repeat statements a specific number of times. The following looping

The following looping statemestatements are available in nts are available in VBScript:VBScript: •

• Do...LoopDo...Loop: Loops while or until a condition is True.: Loops while or until a condition is True. •

• While...WendWhile...Wend: Loops while a condition is True.: Loops while a condition is True. •

• For...NextFor...Next: Uses a counter to run statements a specified number of times.: Uses a counter to run statements a specified number of times. •

• For Each...NextFor Each...Next: Repeats a group of statements for each item in a collection or each: Repeats a group of statements for each item in a collection or each element of an array.

element of an array. VBScript Procedures

VBScript Procedures

In VBScript, there are two kinds of

In VBScript, there are two kinds of procedures; theprocedures; the SubSubprocedure and theprocedure and the FunctionFunctionprocedure.procedure. Sub Procedures

Sub Procedures A

A SuSub b prprococededurure e is is a a seseriries es of of VBVBScScriript pt ststatatememenents ts (e(encnclolosesed d by by SuSub b anand d EnEnd d SuSubb stat

statemeements) that nts) that perfoperform rm actioactions ns but don't but don't retureturn rn a a valuvalue. e. A A Sub proceduSub procedure re can take can take arguargumenmentsts (constants, variables, or expressions that are passed by a calling procedure). If a Sub procedure has (constants, variables, or expressions that are passed by a calling procedure). If a Sub procedure has no arguments, its Sub statement must include an empty set of parentheses ().

no arguments, its Sub statement must include an empty set of parentheses (). The following Sub procedure uses two intrinsic, or

The following Sub procedure uses two intrinsic, or built-in, VBScript functions,built-in, VBScript functions, MsgBoxMsgBox andand InputBox

InputBox, to prompt a user for information. It then displays the results of a calculation based on that, to prompt a user for information. It then displays the results of a calculation based on that information. The calculation is performed in a

information. The calculation is performed in a Function procedure created using VBScript. The FunctionFunction procedure created using VBScript. The Function procedure is shown after the following discussion.

procedure is shown after the following discussion. Sub ConvertTemp()

Sub ConvertTemp()

temp = InputBox("Please enter the temperature in degrees F.", 1) temp = InputBox("Please enter the temperature in degrees F.", 1) MsgBox "The temperatu

MsgBox "The temperature is re is " & Celsius(temp) & " " & Celsius(temp) & " degrees C."degrees C." End Sub

End Sub Function Procedures Function Procedures

A

A FuncFunction procedtion procedure is ure is a a serieseries s of VBScript statof VBScript statemenements enclosets enclosed d by the by the FuncFunction and tion and EndEnd Function stateme

Function statements. A Function procedure is similar nts. A Function procedure is similar to a Sub procedure, but to a Sub procedure, but can also return a value. Acan also return a value. A Function procedure can take argument

Function procedure can take arguments (constants, variables, or expressions that are passed to it by s (constants, variables, or expressions that are passed to it by aa calling procedure). If a Function procedure has no arguments, its Function statement must include an calling procedure). If a Function procedure has no arguments, its Function statement must include an empty set of parentheses. A Function returns a value by assigning a value to its name in one or more empty set of parentheses. A Function returns a value by assigning a value to its name in one or more statements of the procedure. The return type of a Function is always a Variant.

statements of the procedure. The return type of a Function is always a Variant. In

In the following examplethe following example, , the Celsius function calculatthe Celsius function calculates es degredegrees es CelsCelsius ius from degreesfrom degrees Fahrenheit. When the function is called from the ConvertTemp Sub procedure, a variable containing the Fahrenheit. When the function is called from the ConvertTemp Sub procedure, a variable containing the argument value is passed to the function. The result of the calculation is returned to the calling argument value is passed to the function. The result of the calculation is returned to the calling procedure and displayed in a message box.

procedure and displayed in a message box. Sub ConvertTemp()

Sub ConvertTemp()

temp = InputBox("Please enter the temperature in degrees F.", 1) temp = InputBox("Please enter the temperature in degrees F.", 1) MsgBox "The temperatu

MsgBox "The temperature is re is " & Celsius(temp) & " " & Celsius(temp) & " degrees C."degrees C." End Sub

End Sub Function

Function Celsius(fDegreCelsius(fDegrees)es)

Celsius = (fDegrees - 32) * 5 / 9 Celsius = (fDegrees - 32) * 5 / 9 End Function

(2)

Getting Data into and out of

Getting Data into and out of ProceduProceduresres

Each piece of data is passed into your procedures using an argument . Arguments serve as Each piece of data is passed into your procedures using an argument . Arguments serve as placeholders for the data you want to pass into your procedure. You can name your arguments any placeholders for the data you want to pass into your procedure. You can name your arguments any vali

valid d variavariable name. When ble name. When you create a you create a proceprocedure using either the dure using either the Sub statemSub statement or ent or the Functiothe Functionn statement, parentheses must be included after the name of the procedure. Any arguments are placed statement, parentheses must be included after the name of the procedure. Any arguments are placed inside these parentheses

inside these parentheses, separated by commas. For , separated by commas. For example, in the following example, example, in the following example, fDegrees is afDegrees is a placeholder for the value being passed into the Celsius function for

placeholder for the value being passed into the Celsius function for conversion.conversion. Function

Function Celsius(fDegreCelsius(fDegrees)es)

Celsius = (fDegrees - 32) * 5 / 9 Celsius = (fDegrees - 32) * 5 / 9 End Function

End Function

To get data out of a procedure, you must use a Function. Remember, a Function procedure To get data out of a procedure, you must use a Function. Remember, a Function procedure can return a value; a Sub

can return a value; a Sub procedure can't.procedure can't. Using Sub and Function Procedures in Code Using Sub and Function Procedures in Code

A Function in your code must always be used on the right side of a variable assignment or in A Function in your code must always be used on the right side of a variable assignment or in an expression. For example:

an expression. For example: Temp = Celsius(fDegrees) Temp = Celsius(fDegrees)

-or-MsgBox "The Celsius temperatu

MsgBox "The Celsius temperature is " re is " & Celsius(fDegrees) & " degrees."& Celsius(fDegrees) & " degrees."

To call a Sub procedure from another procedure, type the name of the procedure along with To call a Sub procedure from another procedure, type the name of the procedure along with values for any required arguments, each separated by a comma. The

values for any required arguments, each separated by a comma. The CallCall statement is not required,statement is not required, but if you do use it, you must enclose any arguments in parentheses.

but if you do use it, you must enclose any arguments in parentheses. The following example shows two calls

The following example shows two calls to the MyProc procedure. One to the MyProc procedure. One uses the Call statementuses the Call statement in the code; the other doesn't. Both do exactly the same thing.

in the code; the other doesn't. Both do exactly the same thing. Call MyProc(firstarg, secondarg)

Call MyProc(firstarg, secondarg) MyProc firstarg, secondarg MyProc firstarg, secondarg

Notice that the parentheses are omitted in the call when the Call statement isn't used. Notice that the parentheses are omitted in the call when the Call statement isn't used. CreateObject Function CreateObject Function See Also See Also GetObject Function GetObject Function

Creates and returns a reference to an Automation object. Creates and returns a reference to an Automation object. CreateObject(

CreateObject( servernameservername..typenametypename [,[, locationlocation])]) Arguments

Arguments

servername servername

Required. The name of the

Required. The name of the application providing the object.application providing the object. typename

typename

Required. The type or class of the object to create. Required. The type or class of the object to create. location

location

Optional. The name of the network server where the object is to be created. Optional. The name of the network server where the object is to be created. Remarks

Remarks Aut

Automatomation ion servservers ers proviprovide de at at leasleast t one type one type of of objeobject. For ct. For examexample, a ple, a word-word-proceprocessingssing application may provide an application object, a document object, and a toolbar object.

application may provide an application object, a document object, and a toolbar object. T

To o creacreate te an an AutAutomatomation ion objeobject, ct, assigassign n the object returnethe object returned d by by CreaCreateObteObject to ject to an an objeobjectct variable:

variable:

Dim ExcelSheet Dim ExcelSheet

Set ExcelSheet = CreateObject("Excel.Sheet") Set ExcelSheet = CreateObject("Excel.Sheet") This code starts the

This code starts the appliapplicatiocation n thathat t creacreates the tes the objeobject (in ct (in this case, a this case, a MicrosMicrosoft Exceloft Excel spreadsheet). Once an object is created, refer to it in code using the object variable you defined. As spreadsheet). Once an object is created, refer to it in code using the object variable you defined. As shown in the following example, you can access properties and methods of the new object using the shown in the following example, you can access properties and methods of the new object using the obj

object ect vavariariableble, , ExExcelcelShSheeeet, t, anand d othother er ExcExcel el objobjecects, ts, incincludluding ing the the AppAppliclicatiation on objobject ect anand d ththee ActiveSheet.Cells collection:

ActiveSheet.Cells collection:

' Make Excel visible through the Application object. ' Make Excel visible through the Application object. ExcelSheet.Application.Visible = True

ExcelSheet.Application.Visible = True ' Place some text in

' Place some text in the first cell of the first cell of the sheet.the sheet.

ExcelSheet.ActiveSheet.Cells(1,1).Value = "This is column A, row 1" ExcelSheet.ActiveSheet.Cells(1,1).Value = "This is column A, row 1" ' Save the sheet.

' Save the sheet.

ExcelSheet.SaveAs "C:\DOCS\TEST.XLS" ExcelSheet.SaveAs "C:\DOCS\TEST.XLS" ' Close Excel with the Quit method on

' Close Excel with the Quit method on the Application object.the Application object. ExcelSheet.Application.Quit

ExcelSheet.Application.Quit ' Release the object variable. ' Release the object variable. Set ExcelSheet = Nothing Set ExcelSheet = Nothing

Creating an object on a remote server can only be accomplished when Internet security is Creating an object on a remote server can only be accomplished when Internet security is turned off. You can create an object on a remote networked computer by passing the name of the turned off. You can create an object on a remote networked computer by passing the name of the computer to the servername argument of CreateObject. That name is the same as the machine name computer to the servername argument of CreateObject. That name is the same as the machine name por

portiotion n of of a a shashare re naname. me. FoFor r a a nenetwtwork ork shshare are nanamemed d "\\"\\mysmyserverver\er\pubpubliclic", ", ththe e serservevernarname me isis "myserver". In addition, you can specify servername using DNS format or

(3)

The following code returns the version number of an instance of Excel running on a remote The following code returns the version number of an instance of Excel running on a remote network computer named "myserver":

network computer named "myserver": Function GetVersion

Function GetVersion Dim XLApp

Dim XLApp Set XLApp

Set XLApp = CreateObject("Exce= CreateObject("Excel.Application", "MyServer")l.Application", "MyServer") GetVersion = XLApp.Version

GetVersion = XLApp.Version End Function

End Function An error occurs if

An error occurs if the specified remote server does not exist or the specified remote server does not exist or cannot be found.cannot be found. Dim Statement

Dim Statement

Declares variables and allocates storage space. Declares variables and allocates storage space. Dim

Dim varnamevarname[([[([subscriptssubscripts])][,])][, varnamevarname[([[([subscriptssubscripts])]] . . .])]] . . . Arguments

Arguments

varname varname

Name of the variable;

Name of the variable; follows standard variable naming conventions.follows standard variable naming conventions. subscripts

subscripts Dim

Dimenensiosions ns of of an an arrarray ay vavariariableble; ; up up to to 60 60 mulmultiptiple le dimdimenensiosions ns may may be be dedeclaclaredred. . TheThe subscripts argument uses the following syntax:

subscripts argument uses the following syntax: upperbound [,upperbou

upperbound [,upperbound] . . nd] . . ..

The lower bound of an array is always zero. The lower bound of an array is always zero. Remarks

Remarks

Variables decla

Variables declared with Dim at red with Dim at the script level are available to all procedures within the script.the script level are available to all procedures within the script. At the procedure level, variables are

At the procedure level, variables are available only within the procedure.available only within the procedure.

You can also use the Dim statement with empty parentheses to declare a dynamic array. After You can also use the Dim statement with empty parentheses to declare a dynamic array. After decla

declaring a ring a dynadynamic arraymic array, , use the use the ReDReDim im statstatemeement within a nt within a procprocedure to edure to defindefine e the numbethe number r of of  dimensions and elements in the array. If you try to redeclare a dimension for an array variable whose dimensions and elements in the array. If you try to redeclare a dimension for an array variable whose size was explicitly specified in a

size was explicitly specified in a Dim statementDim statement, an error , an error occurs.occurs. Note

Note When you use thWhen you use the Dim statemee Dim statement in a procedure, you gennt in a procedure, you generally put the Dim staterally put the Dim statementement at the beginning of the procedure.

at the beginning of the procedure.

The following examples illustrate the use

The following examples illustrate the use of the Dim of the Dim statemenstatement:t: Dim

Dim Names(9) Names(9) ' ' Declare Declare an an array array with with 10 10 elements.elements. Dim

Dim Names() Names() ' ' Declare Declare a a dynamic dynamic array.array. Dim

Dim MyVarMyVar, , MyNum MyNum ' ' Declare two Declare two variables.variables. Erase Statement

Erase Statement

Reinitializes the elements of fi

Reinitializes the elements of fi xed-size arrays and xed-size arrays and deallocates dynamic-arradeallocates dynamic-array storage y storage space.space. Erase array

Erase array

The array argument is the name of the array variable to be erased. The array argument is the name of the array variable to be erased. Remarks

Remarks

It is important to know whether an array is

It is important to know whether an array is fixed-size (ordinary) or dynamic because Erasefixed-size (ordinary) or dynamic because Erase behaves differently depending on the type of array. Erase recovers no memory for fixed-size arrays. behaves differently depending on the type of array. Erase recovers no memory for fixed-size arrays. Erase sets the elements of a fixed array as fol

Erase sets the elements of a fixed array as fol lows:lows: T

Tyyppe e oof f aarrrraayy EEffffeecct t oof f EErraasse e oon n ffiixxeedd--aarrrraay y eelleemmeennttss F

Fiixxeed d nnuummeerriic c aarrrraayy SSeetts s eeaacch h eelleemmeennt t tto o zzeerroo.. F

Fiixxeed d ssttrriinng g aarrrraayy SSeetts s eeaacch h eelleemmeennt t tto o zzeerroo--lleennggtth h (("""")).. A

Arrrraay y oof f oobbjjeeccttss SSeetts s eeaacch h eelleemmeennt t tto o tthhe e ssppeecciiaal l vvaalluue e NNootthhiinngg.. Era

Erase se freefrees s the memorthe memory y used by used by dynadynamic arrays. Before your program can mic arrays. Before your program can referefer r to theto the dynamic array again, it

dynamic array again, it must redeclare the array variable's dimensions using must redeclare the array variable's dimensions using a ReDim statement.a ReDim statement. The following example illustrates the use of the Erase statement.

The following example illustrates the use of the Erase statement. Dim NumArray(9)

Dim NumArray(9) Dim

Dim DynamicArrayDynamicArray()() ReDim

ReDim DynamicArrayDynamicArray(9) (9) ' ' Allocate Allocate storage storage space.space. Erase

Erase NumArray NumArray ' Each ' Each element element is reinitis reinitialized.ialized. Erase

Erase DynamicArDynamicArray ray ' ' Free Free memory used memory used by by array.array. On Error Statement

On Error Statement

Enables or disables

Enables or disables error-handling.error-handling. On Error Resume Next

On Error Resume Next On Error GoTo 0 On Error GoTo 0 Remarks

Remarks

If you don't use an On Error Resume Next statement anywhere in your code, any run-time If you don't use an On Error Resume Next statement anywhere in your code, any run-time error that occurs can cause an error message to be displayed and code execution stopped. However, error that occurs can cause an error message to be displayed and code execution stopped. However, the host running the

the host running the code determines the exact behaviorcode determines the exact behavior. The . The host can sometimes opt host can sometimes opt to handle suchto handle such errors differently

errors differently. In . In some cases, the script some cases, the script debugger may be invoked at debugger may be invoked at the point of the point of the errorthe error. In . In stillstill other cases, there may be no apparent indication that any error

other cases, there may be no apparent indication that any error occurred because the host does not tooccurred because the host does not to notify the user. Again, this is purely a function of how the host handles any errors that occur.

(4)

Within any particular procedure, an error is not necessarily fatal as long as error-handling is Within any particular procedure, an error is not necessarily fatal as long as error-handling is enabled somewhere along the call stack. If local error-handling is not enabled in a procedure and an enabled somewhere along the call stack. If local error-handling is not enabled in a procedure and an error occurs, contro

error occurs, control l is is passpassed ed back througback through h the call the call stastack ck untuntil il a a proceprocedure with dure with errorerror-han-handlingdling enabled is found and the error is handled at that point. If no procedure in the call stack is found to enabled is found and the error is handled at that point. If no procedure in the call stack is found to have error-handling enabled, an error message is displayed at that point and execution stops or the have error-handling enabled, an error message is displayed at that point and execution stops or the host handles the error as appropriate.

host handles the error as appropriate.

On Error Resume Next causes execution to continue with the statement immediately following On Error Resume Next causes execution to continue with the statement immediately following the statement that caused the run-time error, or with the statement immediately following the most the statement that caused the run-time error, or with the statement immediately following the most recent call out of the

recent call out of the procedure containing the On Error Resume Next statement. This allows executionprocedure containing the On Error Resume Next statement. This allows execution to continue despite a run-time error. You can then build the error-handling routine inline within the to continue despite a run-time error. You can then build the error-handling routine inline within the procedure.

procedure.

An On Error Resume Next statement becomes inactive when another procedure is called, so An On Error Resume Next statement becomes inactive when another procedure is called, so you should execute an On Error Resume Next statement in each called routine if you want inline error you should execute an On Error Resume Next statement in each called routine if you want inline error han

handling within that dling within that routroutine. When ine. When a a procprocedure is edure is exitexited, the ed, the errorerror-han-handling capabilidling capability ty revereverts rts toto whateve

whatever error-handling was r error-handling was in place before entering in place before entering the exited procedure.the exited procedure. Use On Error GoTo 0 to disable error handling if

Use On Error GoTo 0 to disable error handling if you have previously enabled it using On you have previously enabled it using On ErrorError Resume Next.

Resume Next.

The following example illustrates use of the On Error Resume Next statement. The following example illustrates use of the On Error Resume Next statement. On Error Resume Next

On Error Resume Next Err

Err.Raise 6 .Raise 6 ' ' Raise an Raise an overflow erroroverflow error..

MsgBox "Error # " & CStr(Err.Number) & " " & Err.Description MsgBox "Error # " & CStr(Err.Number) & " " & Err.Description Err

Err.Clear .Clear ' ' Clear Clear the the error.error. Option Explicit

Option Explicit StatementStatement

Forces explicit declaration of all variables in a Forces explicit declaration of all variables in a script.script. Option Explicit

Option Explicit Remarks

Remarks

If used, the Option Explicit statement must appear in a script before any other statements. If used, the Option Explicit statement must appear in a script before any other statements. When you use the Option Explicit statement, you must explicitly declare all variables using the When you use the Option Explicit statement, you must explicitly declare all variables using the Dim, Privat

Dim, Private, Public, or e, Public, or ReDiReDim m statstatemenements. If ts. If you attemyou attempt pt to use to use an undeclaran undeclared variable name, aned variable name, an error occurs.

error occurs. Tip

Tip Use OptioUse Option Explicit to avoid incorn Explicit to avoid incorrectly typrectly typing the name of an ing the name of an existexisting variabing variable or le or toto avoid confusion in code where the scope of the variable is not clear.

avoid confusion in code where the scope of the variable is not clear. The following example illustrates use of

The following example illustrates use of the Option Explicit the Option Explicit statemestatement.nt. Option

Option Explicit Explicit ' F' Force exporce explicit variablicit variable declale declaration.ration. Dim

Dim MyVar MyVar ' ' Declare Declare variable.variable. MyInt =

MyInt = 10 10 ' ' Undeclared variable generates Undeclared variable generates error.error. MyVar

MyVar = 10 = 10 ' Declared ' Declared variable does not variable does not generate errorgenerate error..

Create Method 

Create Method 

Description

Description

Creates a new, empty description object in which you can add 

Creates a new, empty description object in which you can add 

collection of properties and values in order to specify the

collection of properties and values in order to specify the

description object in place of a test object name in a step.

description object in place of a test object name in a step.

Syntax 

Syntax 

set

set PropertiesColl 

PropertiesColl =

= Description.Create

Description.Create

Example

Example

The following example uses the

The following example uses the Create

Create method to return a

method to return a Properties

Properties

collection object named EditDescription, and then

(5)

object to instruct QuickTest to enter the text: MyName i

object to instruct QuickTest to enter the text: MyName in the first

n the first

WebEdit

WebEdit object in the Mercury

object in the Mercury T

Tours page with

ours page with the name UserName.

the name UserName.

set EditDesc = Description.Create()

set EditDesc = Description.Create()

EditDesc("Name").Value = "userName"

EditDesc("Name").Value = "userName"

EditDesc("Inde

EditDesc("Index").Value = x").Value = "0""0"

Browser("Welcome: Mercury").Page("Welcome: Mercury").WebEdit(EditDesc).Set "MyName"

Browser("Welcome: Mercury").Page("Welcome: Mercury").WebEdit(EditDesc).Set "MyName"

Environment Object 

Environment Object 

 Description

 Description

Enables you to work with environment variables.

Enables you to work with environment variables.

Y

You can set or retrieve the

ou can set or retrieve the value of environment variables using the Env

value of environment variables using the Environment object.

ironment object.

Y

You can retrieve

ou can retrieve the value of

the value of any environment variable. Y

any environment variable. You can set

ou can set the value of

the value of only

only

user-defined, environment variables.

user-defined, environment variables.

 Syntax 

 Syntax 

T

To set the value of

o set the value of a user-defined, environment variable:

a user-defined, environment variable:

Environment (

Environment (

VariableNameVariableName

) =

) =

 NewValue NewValue

To retrieve the value of a loaded environment variable:

To retrieve the value of a loaded environment variable:

CurrValue

CurrValue

=

=

Environment (

Environment (

VariableNameVariableName

))

Argument

Argument

T

Type

ype

Description

Description

VariableName

VariableName

String

String

The

The name

name of

of the

the environment

environment variable.

variable.

 NewValue

 NewValue

V

Variant

ariant

The new

The

new value

value of

of the

the environment

environment variable.

variable.

CurrValue

CurrValue

V

Variant

ariant

The current

The

current value

value of

of the

the environment

environment variable.

variable.

 Example

 Example

The following example

The following example creates a new

creates a new internal user-defined variable named M

internal user-defined variable named MyV

yVariable

ariable

with a value of 10,

with a value of 10, and then retrieves the variable value

and then retrieves the variable value and stores it in the MyV

and stores it in the MyValue

alue

variable.

(6)

Environment.Value("MyVariable")=10

Environment.Value("MyVariable")=10

MyValue=Environment.Value("MyVariable")

MyValue=Environment.Value("MyVariable")

Parameter Object 

Parameter Object 

 Description

 Description

An input or output action

An input or output action or component parameter.

or component parameter.

This object can be used in the parameterized value of a step or in a call to an action in

This object can be used in the parameterized value of a step or in a call to an action in

order to parameterize the value of one of the input parameters supplied to the called

order to parameterize the value of one of the input parameters supplied to the called

action or to indicate the storage location for one of the output parameters supplied to the

action or to indicate the storage location for one of the output parameters supplied to the

called action.

called action.

For more information on supplying parameters when calling an

For more information on supplying parameters when calling an action, see

action, see RunAction

RunAction

Statement

Statement

..

 Syntax 

 Syntax 

Parameter(

Parameter(

 ParamName ParamName

))

Argument

Argument

T

Type

ype

Description

Description

 ParamName

 ParamName

String

String

The

The name

name of

of the

the action,

action, or

or component

component parameter

parameter..

 Example

 Example

Suppose you have test steps that enter information in a form in order to display a list of 

Suppose you have test steps that enter information in a form in order to display a list of 

 purchase orders in a table, a

 purchase orders in a table, and then return the total value

nd then return the total value of the orders displayed in the

of the orders displayed in the

table.

table.

Y

You can define

ou can define input parameters, called

input parameters, called

SoldToCode

SoldToCode

and

and

MaterialCode

MaterialCode

, for the codes

, for the codes

entered in the

entered in the

Sold to

Sold to

and

and

Materials

Materials

edit boxes of the form so that the

edit boxes of the form so that the Orders table that is

Orders table that is

opened is controlled by the

opened is controlled by the input parameter values passed when the

input parameter values passed when the test is called.

test is called.

Y

You can define

ou can define an output parameter, called

an output parameter, called

TotalValue

TotalValue

, to store the returned value. The

, to store the returned value. The

output value (

output value (

TotalValue

TotalValue

) could then be returned to the application that called the test.

) could then be returned to the application that called the test.

The example described above might look something like this (parameters are in bold

The example described above might look something like this (parameters are in bold

font):

(7)

Browser("Mercury").Page("List Of

Browser("Mercury").Page("List Of Sales").W

Sales").WebEdit("Sold to").Set

ebEdit("Sold to").Set

Parameter("

Parameter("

SoldToCode

SoldToCode

")

")

Browser("Mercury").Page("List Of

Browser("Mercury").Page("List Of Sales").W

Sales").WebEdit("Materials").Set

ebEdit("Materials").Set

Parameter("

Parameter("

MaterialCode

MaterialCode

")

")

Browser("Mercury").Page("List Of

Browser("Mercury").Page("List Of Sales").W

Sales").WebButton("Enter").Click 

ebButton("Enter").Click 

 NumT

 NumTableRows =

ableRows = Browser("Mercury").Page("List Of 

Browser("Mercury").Page("List Of 

Sales").W

Sales").WebT

ebTable("Orders").RowCount

able("Orders").RowCount

Parameter("

Parameter("

TotalValue

TotalValue

") = Browser("Mercury").Page("List Of 

") = Browser("Mercury").Page("List Of 

Sales").WebTable("Orders").GetCellData(NumTableRows,"Total")

Sales").WebTable("Orders").GetCellData(NumTableRows,"Total")

IMP 

IMP 

Generating Automation Scripts

Generating Automation Scripts

The Properties tab of the Test Settings dialog box, the General tab of the Options dialog

The Properties tab of the Test Settings dialog box, the General tab of the Options dialog

 box, and the Object Identification dialog box each contain a

 box, and the Object Identification dialog box each contain a

Generate Script

Generate Script

button.

button.

Clicking this button generates an automation

Clicking this button generates an automation script file (

script file (

.vbs

.vbs

) containing the current

) containing the current

settings from the corresponding dialog box.

settings from the corresponding dialog box.

Y

You can run the g

ou can run the generated script as is to open QuickTest with the exact configuration of 

enerated script as is to open QuickTest with the exact configuration of 

the QuickTest application that generated the script, or you can copy and

the QuickTest application that generated the script, or you can copy and paste selected

paste selected

lines from the generated files into your own automation script.

lines from the generated files into your own automation script.

For example, the generated script for the

For example, the generated script for the Options dialog box may look something like

Options dialog box may look something like

this:

this:

Dim App 'As Application

Dim App 'As Application

Set App =

Set App =

CreateObject("QuickT

CreateObject("QuickT

est.Application")

est.Application")

App.Launch

App.Launch

App.Visible = True

App.Visible = True

App.Options.DisableVORecognition = False

App.Options.DisableVORecognition = False

App.Options.AutoGenerateWith = False

App.Options.AutoGenerateWith = False

App.Options.WithGenerationLevel = 2

App.Options.WithGenerationLevel = 2

(8)

App.Options.TimeT

App.Options.TimeT

oActivateWinAfter

oActivateWinAfterPoint

Point =

= 500

500

..

..

..

..

App.Options.WindowsApps.NonUniqueLis

App.Options.WindowsApps.NonUniqueListItemRecordMode =

tItemRecordMode = "ByName"

"ByName"

App.Options.WindowsApps.RecordOwnerD

App.Options.WindowsApps.RecordOwnerDrawnButtonAs =

rawnButtonAs = "PushButtons"

"PushButtons"

App.Folders.RemoveAll

App.Folders.RemoveAll

For more information on the

For more information on the

Generate Script

Generate Script

button and for information on the options

button and for information on the options

available in the

available in the Options, Object Identification, Test Settings, and Business Component

Options, Object Identification, Test Settings, and Business Component

Settings dialog boxes, see

Settings dialog boxes, see Setting Global Testing Options,

Setting Global Testing Options,

Configuring Object

Configuring Object

Identification,

Identification,

, and

, and Setting Options for Individual Tests or Components

Setting Options for Individual Tests or Components

respectively.

respectively.

Example: Display the Number of Objects Found that

Example: Display the Number of Objects Found that Match a Specified Description

Match a Specified Description

'The following example uses the ChildObjects method to retrieve a set

'The following example uses the ChildObjects method to retrieve a set

'of child objects matching the description listed in the function call,

'of child objects matching the description listed in the function call,

'and uses the method to display a message indicating how many objects

'and uses the method to display a message indicating how many objects

'are found with the specified description: none, one (unique), or

'are found with the specified description: none, one (unique), or

'several (not unique).

'several (not unique).

Public

Public FunctionFunction CheckObjectDesription(parent, descr)CheckObjectDesription(parent, descr) Dim

Dim oDescoDesc

' Create description object

' Create description object

Set

Set oDesc = Description.Create()oDesc = Description.Create() arProps =

arProps = SplitSplit(descr,(descr, ","",")) For

For i = 0i = 0 ToTo UBoundUBound(arProps)(arProps) arProp =

arProp = SplitSplit(arProps(i),(arProps(i), ":="":=")) If

If UBoundUBound(arProp) = 1(arProp) = 1 ThenThen

PropName = Trim(arProp(0)) PropName = Trim(arProp(0)) PropValue = arProp(1) PropValue = arProp(1) oDesc(PropName).Value = PropValue oDesc(PropName).Value = PropValue End End IfIf Next Next

' Get all child objects with the given description

' Get all child objects with the given description

Set

Set children = parent.ChildObjects(oDesc)children = parent.ChildObjects(oDesc)

If

(9)

CheckObjectDesription =

CheckObjectDesription = "Object Unique""Object Unique"

ElseIf

ElseIf children.Count = 0children.Count = 0 ThenThen

CheckObjectDesription =

CheckObjectDesription = "Object Not Found""Object Not Found"

Else

Else

CheckObjectDesription =

CheckObjectDesription = "Object Not Unique""Object Not Unique"

End

End IfIf

End

End FunctionFunction

VBScript Features

VBScript Features

The following table is a list of VBScript features.

The following table is a list of VBScript features.

C

Ca

atteeg

go

orry

y

K

Keey

yw

wo

orrd

dss

Array handling

Array handling

Array

Array

Dim

Dim

,, Private

Private

,, Public

Public

,, ReDim

ReDim

IsArray

IsArray

Erase

Erase

LBound

LBound

,, UBound

UBound

Assignments

Assignments

Set

Set

Comments

Comments

Comments using ' or Rem

Comments using ' or Rem

Constants/Literals

Constants/Literals Empty

Empty

 Nothing

 Nothing

 Null

 Null

True

True

,, False

False

Control flow

Control flow

Do...Loop

Do...Loop

For...Next

For...Next

For Each...Next

For Each...Next

If...Then...Else

If...Then...Else

Select Case

Select Case

While...Wend

While...Wend

With

With

Conversions

Conversions

Abs

Abs

Asc, AscB, AscW

Asc, AscB, AscW

Chr, ChrB, ChrW

Chr, ChrB, ChrW

CBool

CBool

,, CByte

CByte

CCur 

CCur 

,, CDate

CDate

CDbl

CDbl

,, CInt

CInt

CLng

CLng

,, CSng

CSng

,, CStr 

CStr 

DateSerial

DateSerial

,, DateValue

DateValue

Hex

Hex

,, Oct

Oct

Fix

Fix

,, Int

Int

Sgn

Sgn

TimeSerial

(10)

Dates/Times

Dates/Times

Date

Date

,, Time

Time

DateAdd

DateAdd

,, DateDiff 

DateDiff 

,, DatePart

DatePart

DateSerial

DateSerial

,, DateValue

DateValue

Day

Day

,, Month

Month

,, MonthName

MonthName

Weekday

Weekday

,, WeekdayName

WeekdayName

,, Year 

Year 

Hour 

Hour 

,, Minute

Minute

,, Second

Second

 Now

 Now

TimeSerial

TimeSerial

,, TimeValue

TimeValue

Declarations

Declarations

Class

Class

Const

Const

Dim

Dim

,, Private

Private

,, Public

Public

,, ReDim

ReDim

Function

Function

,, Sub

Sub

Property Get

Property Get

,, Property Let

Property Let

,, Property Set

Property Set

Error Handling

Error Handling

On Error 

On Error 

Err 

Err 

Expressions

Expressions

Eval

Eval

Execute

Execute

RegExp

RegExp

Replace

Replace

Test

Test

Formatting Strings

Formatting Strings FormatCurrency

FormatCurrency

FormatDateTime

FormatDateTime

FormatNumber 

FormatNumber 

FormatPercent

FormatPercent

Input/Output

Input/Output

InputBox

InputBox

LoadPicture

LoadPicture

MsgBox

MsgBox

Literals

Literals

Empty

Empty

False

False

 Nothing

 Nothing

 Null

 Null

True

True

Math

Math

Atn

Atn

,, Cos

Cos

,, Sin

Sin

,, T

T

an

an

Exp

Exp

,, Log

Log

,, Sqr 

Sqr 

Randomize

Randomize

,, Rnd

Rnd

Miscellaneous

Miscellaneous

Eval Function

Eval Function

Execute Statement

Execute Statement

RGB Function

RGB Function

Objects

Objects

CreateObject

CreateObject

Err Object

Err Object

GetObject

GetObject

RegExp

RegExp

Operators

Operators

Addition (+)

Addition (+)

,, Subtraction (-)

Subtraction (-)

Exponentiation (^)

Exponentiation (^)

Modulus arithmetic (Mod)

(11)

Multiplication (*)

Multiplication (*)

,, Division (/)

Division (/)

Integer Division (\)

Integer Division (\)

 Negation (-)

 Negation (-)

String concatenation (&)

String concatenation (&)

Equality (=)

Equality (=)

,, Inequality (<>)

Inequality (<>)

Less Than (<)

Less Than (<)

,, Less Than or Equa

Less Than or Equa

l T

l T

o (<=)

o (<=)

Greater Than (>)

Greater Than (>)

Greater Than or Equal To (>=)

Greater Than or Equal To (>=)

Is

Is

And

And

,, Or 

Or 

,, Xor 

Xor 

Eqv

Eqv

,, Imp

Imp

Options

Options

Option Explicit

Option Explicit

Procedures

Procedures

Call

Call

Function

Function

,, Sub

Sub

Property Get

Property Get

,, Property Let

Property Let

,, Property Set

Property Set

Rounding

Rounding

Abs

Abs

Int

Int

,, Fix

Fix

,, Round

Round

Sgn

Sgn

Script Engine ID

Script Engine ID

ScriptEngine

ScriptEngine

ScriptEngineBuildVersion

ScriptEngineBuildVersion

ScriptEngineMajorVersion

ScriptEngineMajorVersion

ScriptEngineMinorVersion

ScriptEngineMinorVersion

Strings

Strings

Asc

Asc

,, AscB

AscB

,, AscW

AscW

Chr 

Chr 

,, ChrB

ChrB

,, ChrW

ChrW

Filter 

Filter 

,, InStr 

InStr 

,, InStrB

InStrB

InStrRev

InStrRev

Join

Join

Len

Len

,, LenB

LenB

LCase

LCase

,, UCase

UCase

Left

Left

,, LeftB

LeftB

Mid

Mid

,, MidB

MidB

Right

Right

,, RightB

RightB

Replace

Replace

Space

Space

Split

Split

StrComp

StrComp

String

String

StrReverse

StrReverse

LTrim

LTrim

,, RTrim

RTrim

,, Trim

Trim

Variants

Variants

IsArray

IsArray

IsDate

IsDate

IsEmpty

IsEmpty

IsNull

IsNull

IsNumeric

IsNumeric

IsObject

IsObject

TypeName

TypeName

(12)

VarType

VarType

Regular Expression (RegExp) Object

Regular Expression (RegExp) Object

See Also

See Also

Match Object

Match Object

|| Matches Collection

Matches Collection

Requirements

Requirements

V

V

ersion

ersion

5

5

Provides simple regular expression support.

Provides simple regular expression support.

Remarks

Remarks

The following code illustrates the use of the

The following code illustrates the use of the

RegExp

RegExp

object.

object.

Function RegExpTest(patrn, strng) Function RegExpTest(patrn, strng)

Dim

Dim regEx, regEx, Match, Match, Matches Matches ' ' Create Create variable.variable. Set regEx = New

Set regEx = New RegExpRegExp ' Create a regular expression.' Create a regular expression. regEx.Pattern

regEx.Pattern = = patrn patrn ' ' Set Set pattern.pattern. regEx.IgnoreCase

regEx.IgnoreCase = = True True ' ' Set Set case case insensitivity.insensitivity. regEx.Global

regEx.Global = = True True ' ' Set Set global global applicability.applicability. Set

Set Matches Matches = = regEx.Execute(strng) regEx.Execute(strng) ' ' Execute Execute search.search. For

For Each Each Match Match in in Matches Matches ' ' Iterate Iterate Matches Matches collection.collection. RetStr = RetStr & "Match found at position "

RetStr = RetStr & "Match found at position "

RetStr = RetStr & Match.FirstIndex & ". Match Value is '" RetStr = RetStr & Match.FirstIndex & ". Match Value is '" RetStr = RetStr & Match.Value & "'." & vbCRLF

RetStr = RetStr & Match.Value & "'." & vbCRLF Next Next RegExpTest = RetStr RegExpTest = RetStr End Function End Function

MsgBox(RegExpTest("is.", "IS1 is2 IS3 is4")) MsgBox(RegExpTest("is.", "IS1 is2 IS3 is4"))

Properties and Methods

Properties and Methods

Regular Expression Object Properties and Methods

Regular Expression Object Properties and Methods

Requirements

Requirements

V

V

ersion

ersion

5

5

See Also

See Also

Match Object

(13)

References

Related documents

In this study, it is aimed to develop the Science Education Peer Comparison Scale (SEPCS) in order to measure the comparison of Science Education students'

Quality: We measure quality (Q in our formal model) by observing the average number of citations received by a scientist for all the papers he or she published in a given

All the figures and tables should be labeled (Times New Roman 11) and included in list of figures and list of tables respectively.

В середньому кожного року кі- лькість злочинів, пов’язаних з наркотичними, сильнодіючими засобами та прекурсорами зменшувалась на 3911 злочинів або на 8,79%..

Specifically, the risk is considered as the area of the distribution of the arrival time fell after the latest time of the time window, and the mean of the arrival time is

Marketing Theory under a Service Dominant Logic Perspective”, Naples Forum on Service, June 9-12, (2015) Naples, Italy.. troviamo di fronte ad un più alto livello di

11 In addition to the Provisional Regulations on Domain Name Registration, China has draft Regulations on Domain Name Registration Dispute Resolution (“Draft Regulations”).

As consequence, this paper contains a study on the effect of the rotor bar number on the torque (average and quality) of five-phase induction machines under different supply