Vb Script_Good One

Share Embed Donate


Short Description

Download Vb Script_Good One...

Description

VBScript Data Types 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 is used. Because Variant is the only data type in VBScript, it is also the data type returned by all functions in VBScript. At its simplest, a Variant can contain either numeric or string information. A Variant behaves as a number when you use it in a numeric context and as a string when you use it in a string context. That is, if you are working with data that looks like numbers, VBScript assumes that it is numbers and does what is most appropriate for numbers. Similarly, if you're working with data that can only be string data, VBScript treats it as string data. You can always make numbers behave as strings by enclosing them in quotation marks (" "). 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 more places, causing unexpected results when your script is run. For that reason, the Option Explicit statement statement is available to require require explicit explicit declaration declaration of all variables variables.. The Option Explicit statement statement should be the first statement in your script. 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 repeat statements a specific number of times. The following looping statements statements are available in VBScript: •

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



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



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



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

VBScript Procedures In VBScript, there are two kinds of procedures; the Sub procedure and the Function procedure. Sub Procedures A Sub Sub proc proced edur ure e is a seri series es of VBSc VBScri ript pt stat statem emen ents ts (enc (enclo lose sed d by Sub Sub and and End End Sub Sub stateme statements) nts) that perform perform actions actions but don't return return a value. value. A Sub procedure procedure can take argumen arguments ts (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 (). The following Sub procedure uses two intrinsic, or built-in, VBScript functions, MsgBox and InputBox,, to prompt a user for information. It then displays the results of a calculation based on that InputBox information. The calculation is performed in a Function procedure created using VBScript. The Function procedure is shown after the following discussion. Sub ConvertTemp() temp = InputBox("Please enter the temperature in degrees F.", 1) MsgBox "The temperature temperature is " & Celsius(temp) & " degrees C." End Sub Function Procedures A Function Function procedure procedure is a series series of VBScript statemen statements ts enclosed enclosed by the Function Function and End Function statements. statements. A Function procedure is similar to a Sub procedure, but can also return a value. A Function procedure can take arguments arguments (constants, variables, or expressions that are passed to it by a 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 statements of the procedure. The return type of a Function is always a Variant. In the following example, example, the Celsius function calculates calculates degrees degrees Celsius Celsius from degrees 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 procedure and displayed in a message box. Sub ConvertTemp() temp = InputBox("Please enter the temperature in degrees F.", 1) MsgBox "The temperature temperature is " & Celsius(temp) & " degrees C." End Sub Function Celsius(fDegrees) Celsius(fDegrees) Celsius = (fDegrees - 32) * 5 / 9 End Function

Getting Data into and out of Procedures Procedures 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 valid valid variable variable name. When you create a procedure procedure using either the Sub statement statement or the Function Function statement, parentheses must be included after the name of the procedure. Any arguments are placed inside these parentheses, parentheses, separated by commas. For example, in the following example, fDegrees is a placeholder for the value being passed into the Celsius function for conversion. Function Celsius(fDegrees) Celsius(fDegrees) Celsius = (fDegrees - 32) * 5 / 9 End Function To get data out of a procedure, you must use a Function. Remember, a Function procedure can return a value; a Sub procedure can't. 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 an expression. For example: Temp = Celsius(fDegrees) -orMsgBox "The Celsius temperature temperature is " & Celsius(fDegrees) & " degrees." 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 Call statement is not required, but if you do use it, you must enclose any arguments in parentheses. The following example shows two calls to the MyProc procedure. One uses the Call statement in the code; the other doesn't. Both do exactly the same thing. Call MyProc(firstarg, secondarg) MyProc firstarg, secondarg Notice that the parentheses are omitted in the call when the Call statement isn't used. CreateObject Function See Also GetObject Function Creates and returns a reference to an Automation object. CreateObject( servername servername..typename [, location location]) ]) Arguments servername Required. The name of the application providing the object. typename Required. The type or class of the object to create. location Optional. The name of the network server where the object is to be created. Remarks Automat Automation ion servers servers provide provide at least least one type of object. object. For example, example, a word-proce word-processing ssing application may provide an application object, a document object, and a toolbar object. To create create an Automat Automation ion object, object, assign assign the object returned returned by CreateOb CreateObject ject to an object object variable: Dim ExcelSheet Set ExcelSheet = CreateObject("Excel.Sheet") This code starts the applicatio application n that that creates creates the object object (in this case, a Microsoft Microsoft Excel 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 object object varia variable ble,, Excel ExcelSh Shee eet, t, and and other other Excel Excel objec objects, ts, includ including ing the Applic Applicati ation on object object and and the the ActiveSheet.Cells collection: ' Make Excel visible through the Application object. ExcelSheet.Application.Visible = True ' Place some text in the first cell of the sheet. ExcelSheet.ActiveSheet.Cells(1,1).Value = "This is column A, row 1" ' Save the sheet. ExcelSheet.SaveAs "C:\DOCS\TEST.XLS" ' Close Excel with the Quit method on the Application object. ExcelSheet.Application.Quit ' Release the object variable. Set ExcelSheet = Nothing 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 computer to the servername argument of CreateObject. That name is the same as the machine name portio portion n of a share share name. name. For For a netw network ork share share name named d "\\mys "\\myserv erver\ er\pub public lic", ", the the serve serverna rname me is "myserver". In addition, you can specify servername using DNS format or an IP address.

The following code returns the version number of an instance of Excel running on a remote network computer named "myserver": Function GetVersion Dim XLApp Set XLApp = CreateObject("Excel.Application", CreateObject("Excel.Application", "MyServer") GetVersion = XLApp.Version End Function An error occurs if the specified remote server does not exist or cannot be found. Dim Statement Declares variables and allocates storage space. Dim varname varname[([ [([subscripts subscripts])][, ])][, varname varname[([ [([subscripts subscripts])]] ])]] . . . Arguments varname Name of the variable; follows standard variable naming conventions. subscripts Dimen Dimensio sions ns of an array array varia variable ble;; up to 60 multip multiple le dimen dimensio sions ns may be decla declared red.. The subscripts argument uses the following syntax: upperbound [,upperbound] [,upperbound] . . . The lower bound of an array is always zero. Remarks Variables declared declared with Dim at the script level are available to all procedures within the script. At the procedure level, variables are available only within the procedure. You can also use the Dim statement with empty parentheses to declare a dynamic array. After declaring declaring a dynamic dynamic array, array, use the ReDim ReDim stateme statement nt within a procedure procedure to define define the number number of  dimensions and elements in the array. If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Dim statement, statement, an error occurs. Note When you use the the Dim statement statement in a procedure, you generally generally put the Dim statement statement at the beginning of the procedure. The following examples illustrate the use of the Dim statement: statement: Dim Names(9) ' Declare an array with 10 elements. Dim Names() ' Declare a dynamic array. Dim MyVar, MyVar, MyNum ' Declare two variables. Erase Statement Reinitializes the elements of fi xed-size arrays and deallocates dynamic-array dynamic-array storage space. Erase array The array argument is the name of the array variable to be erased. Remarks It is important to know whether an array is fixed-size (ordinary) or dynamic because Erase 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 lows: Type of array Effect of Erase on fixed-array elements Fixed numer ic array Sets each element to zero. Fixed string array Sets each element to zero-length (""). Array of objects Sets each element to the special value Nothing. Erase Erase frees frees the memory memory used by dynamic dynamic arrays. Before your program can refer refer to the dynamic array again, it must redeclare the array variable's dimensions using a ReDim statement. The following example illustrates the use of the Erase statement. Dim NumArray(9) Dim DynamicArray() DynamicArray() ReDim DynamicArray(9) DynamicArray (9) ' Allocate storage space. Erase NumArray ' Each element is reinitialized. reinitialized. Erase DynamicArray DynamicAr ray ' Free memory used by array. On Error Statement Enables or disables error-handling. On Error Resume Next On Error GoTo 0 Remarks 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, the host running the code determines the exact behavior. behavior. The host can sometimes opt to handle such errors differently. differently. In some cases, the script debugger may be invoked at the point of the error. error. In still other cases, there may be no apparent indication that any error occurred because the host does not to notify the user. Again, this is purely a function of how the host handles any errors that occur.

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 error occurs, control control is passed passed back through through the call stack stack until until a procedure procedure with error-han error-handling dling 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 host handles the error as appropriate. 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 recent call out of the procedure 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 procedure. 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 handling handling within that routine. routine. When a procedure procedure is exited, exited, the error-han error-handling dling capability capability reverts reverts to whatever whatever error-handling was in place before entering the exited procedure. Use On Error GoTo 0 to disable error handling if you have previously enabled it using On Error Resume Next. The following example illustrates use of the On Error Resume Next statement. On Error Resume Next Err.Raise Err.Raise 6 ' Raise an overflow error. error. MsgBox "Error # " & CStr(Err.Number) & " " & Err.Description Err.Clear Err.Clear ' Clear the error. Option Explicit Statement Forces explicit declaration of all variables in a script. Option Explicit Remarks 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 Dim, Private, Private, Public, or ReDim ReDim statemen statements. ts. If you attempt attempt to use an undeclared undeclared variable name, an error occurs. Tip Use Option Option Explicit to avoid incorrectly incorrectly typing typing the name of an existing existing variable variable or to avoid confusion in code where the scope of the variable is not clear. The following example illustrates use of the Option Explicit statement. statement. Option Explicit ' Force Force explicit explicit variable variable declaration. declaration. Dim MyVar ' Declare variable. MyInt = 10 ' Undeclared variable generates error. MyVar = 10 ' Declared variable does not generate error. error.

Create Method  Description

Creates a new, empty description object in which you can add  collection of properties and values in order to specify the description object in place of a test object name in a step. Syntax  set PropertiesColl = Description.Create

Example The following example uses the Create method to return a Properties collection object named EditDescription, and then uses the returned

object to instruct QuickTest to enter the text: MyName in i n the first WebEdit object in the Mercury Tours page with the name UserName. set EditDesc = Description.Create() EditDesc("Name").Value = "userName" EditDesc("Index").Value EditDesc("Inde x").Value = "0" Browser("Welcome: Mercury").Page("Welcome: Mercury").WebEdit(EditDesc).Set "MyName"

Environment Object   Description Enables you to work with environment variables. You can set or retrieve the value of environment variables using the Environment Env ironment object. You can retrieve the value of any environment variable. You You can set the value of only user-defined, environment variables.

 Syntax  To set the value of a user-defined, environment variable: Environment ( VariableName) = NewValue

To retrieve the value of a loaded environment variable: CurrValue

= Environment (VariableName)

Argument

Type

Description

String

The name of the environment variable.

 NewValue

Variant

The new value of the environment variable.

CurrValue

Variant

The current value of the environment variable.

VariableName

 Example The following example creates a new internal user-defined variable named MyV M yVariable ariable with a value of 10, and then retrieves the variable value and stores it in the MyValue MyValue variable.

Environment.Value("MyVariable")=10 MyValue=Environment.Value("MyVariable")

Parameter Object   Description An input or output action or component parameter. 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 action or to indicate the storage location for one of the output parameters supplied to the called action. For more information on supplying parameters when calling an action, see RunAction Statement.. Statement

 Syntax  Parameter( ParamName) Argument

Type

 ParamName

String

Description

The name of the action, or component parameter. parameter.

 Example Suppose you have test steps that enter information in a form in order to display a list of   purchase orders in a table, and a nd then return the total value of the orders displayed in the table. You can define input parameters, called SoldToCode and MaterialCode , for the codes entered in the Sold to and Materials edit boxes of the form so that the Orders table that is opened is controlled by the input parameter values passed when the test is called. You can define an output parameter, called TotalValue , to store the returned value. The output value (TotalValue ) could then be returned to the application that called the test. The example described above might look something like this (parameters are in bold font):

Browser("Mercury").Page("List Of Sales").WebEdit("Sold Sales").WebEdit("Sold to").Set Parameter("SoldToCode ") Browser("Mercury").Page("List Of Sales").WebEdit("Materials").Set Sales").WebEdit("Materials").Set Parameter("MaterialCode ") Browser("Mercury").Page("List Of Sales").WebButton("Enter").Click  Sales").WebButton("Enter").Click   NumTableRows  NumTableRows = Browser("Mercury").Page("List Of  Sales").WebT Sales").WebTable("Orders").RowCount able("Orders").RowCount Parameter("TotalValue ") = Browser("Mercury").Page("List Of  Sales").WebTable("Orders").GetCellData(NumTableRows,"Total")

IMP  Generating Automation Scripts 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 Generate Script button. Clicking this button generates an automation script file (.vbs) containing the current settings from the corresponding dialog box. You can run the generated g enerated script as is to open QuickTest with the exact configuration of  the QuickTest application that generated the script, or you can copy and paste selected lines from the generated files into your own automation script. For example, the generated script for the Options dialog box may look something like this: Dim App 'As Application Set App = CreateObject("QuickT CreateObject("QuickTest.Application") est.Application") App.Launch App.Visible = True App.Options.DisableVORecognition = False App.Options.AutoGenerateWith = False App.Options.WithGenerationLevel = 2

App.Options.TimeToActivateWinAfter App.Options.TimeT oActivateWinAfterPoint Point = 500 .. .. App.Options.WindowsApps.NonUniqueListItemRecordMode App.Options.WindowsApps.NonUniqueLis tItemRecordMode = "ByName" App.Options.WindowsApps.RecordOwnerDrawnButtonAs App.Options.WindowsApps.RecordOwnerD rawnButtonAs = "PushButtons" App.Folders.RemoveAll For more information on the Generate Script button and for information on the options available in the Options, Object Identification, Test Settings, and Business Component Settings dialog boxes, see Setting Global Testing Options, Configuring Object Identification,,, and Setting Options for Individual Tests or Components respectively. Identification,

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

'The following example uses the ChildObjects method to retrieve a set 'of child objects matching the description listed in the function call, 'and uses the method to display a message indicating how many objects 'are found with the specified description: none, one (unique), or 'several (not unique).

Public Function CheckObjectDesription(parent, descr) Dim oDesc ' Create description object Set oDesc = Description.Create() arProps = Split Split(descr, (descr, "," ",") ) For i = 0 To UBound UBound(arProps) (arProps) arProp = Split Split(arProps(i), (arProps(i), ":=" ":=") ) If UBound UBound(arProp) (arProp) = 1 Then PropName = Trim(arProp(0)) PropValue = arProp(1) oDesc(PropName).Value = PropValue End If Next ' Get all child objects with the given description Set children = parent.ChildObjects(oDesc) If children.Count = 1 Then

CheckObjectDesription ElseIf children.Count CheckObjectDesription Else CheckObjectDesription End If End Function

= "Object Unique" = 0 Then = "Object Not Found" = "Object Not Unique"

VBScript Features The following table is a list of VBScript features. Category Array handling

Keywords

Array Dim,, Private Dim Private,, Public Public,, ReDim IsArray Erase LBound,, UBound LBound Assignments Set Comments Comments using ' or Rem Constants/Literals Empty  Nothing  Null True,, False True Control flow Do...Loop For...Next For Each...Next If...Then...Else Select Case While...Wend With Conversions Abs Asc, AscB, AscW Chr, ChrB, ChrW CBool,, CByte CBool CCur , CDate CDbl,, CInt CDbl CLng,, CSng CLng CSng,, CStr  DateSerial,, DateValue DateSerial Hex,, Oct Hex Fix,, Int Fix Sgn TimeSerial,, TimeValue TimeSerial

Dates/Times

Date, Time Date, DateAdd,, DateDiff , DatePart DateAdd DateSerial,, DateValue DateSerial Day,, Month Day Month,, MonthName Weekday,, WeekdayName Weekday WeekdayName,, Year  Hour , Minute Minute,, Second  Now TimeSerial,, TimeValue TimeSerial Declarations Class Const Dim,, Private Dim Private,, Public Public,, ReDim Function,, Sub Function Property Get, Get, Property Let, Let, Property Set Error Handling On Error  Err  Expressions Eval Execute RegExp Replace Test Formatting Strings FormatCurrency FormatDateTime FormatNumber  FormatPercent Input/Output InputBox LoadPicture MsgBox Literals Empty False  Nothing  Null True Math Atn,, Cos Atn Cos,, Sin Sin,, Tan Exp,, Log Exp Log,, Sqr  Randomize,, Rnd Randomize Miscellaneous Eval Function Execute Statement RGB Function Objects CreateObject Err Object GetObject RegExp Operators Addition (+), (+), Subtraction (-) Exponentiation (^) Modulus arithmetic (Mod)

Multiplication (*), (*), Division (/) Integer Division (\)  Negation (-) String concatenation (&) Equality (=), (=), Inequality () Less Than (
View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF