Skip to main content

QTP defalut Functions


Functions:

 

Abs Function

Returns the absolute value of a number.
Abs(number)
The number argument can be any valid numeric expression. If number contains Null, Null is returned; if it is an uninitialized variable, zero is returned.

Remarks

The absolute value of a number is its unsigned magnitude. For example, Abs(-1) and Abs(1) both return 1.
The following example uses the Abs function to compute the absolute value of a number:
Dim MyNumber
MyNumber = Abs(50.3)  ' Returns 50.3.
MyNumber = Abs(-50.3) ' Returns 50.3.

Array Function

Returns a Variant containing an array.
Array(arglist)
The required arglist argument is a comma-delimited list of values that are assigned to the elements of an array contained with the Variant. If no arguments are specified, an array of zero length is created.

Remarks

The notation used to refer to an element of an array consists of the variable name followed by parentheses containing an index number indicating the desired element. In the following example, the first statement creates a variable named A. The second statement assigns an array to variable A. The last statement assigns the value contained in the second array element to another variable.
Dim A
A = Array(10,20,30)
B = A(2)   ' B is now 30.
Note   A variable that is not declared as an array can still contain an array. Although a Variant variable containing an array is conceptually different from an array variable containing Variant elements, the array elements are accessed in the same way.

Requirements

Asc Function

Returns the ANSI character code corresponding to the first letter in a string.
Asc(string)
The string argument is any valid string expression. If the string contains no characters, a run-time error occurs.

Remarks

In the following example, Asc returns the ANSI character code of the first letter of each string:
Dim MyNumber
MyNumber = Asc("A")       ' Returns 65.
MyNumber = Asc("a")       ' Returns 97.
MyNumber = Asc("Apple")   ' Returns 65.
Note   The AscB function is used with byte data contained in a string. Instead of returning the character code for the first character, AscB returns the first byte. AscW is provided for 32-bit platforms that use Unicode characters. It returns the Unicode (wide) character code, thereby avoiding the conversion from Unicode to ANSI.

Atn Function

Returns the arctangent of a number.
Atn(number)
The number argument can be any valid numeric expression.

Remarks

The Atn function takes the ratio of two sides of a right triangle (number) and returns the corresponding angle in radians. The ratio is the length of the side opposite the angle divided by the length of the side adjacent to the angle. The range of the result is -pi /2 to pi/2 radians.
To convert degrees to radians, multiply degrees by pi/180. To convert radians to degrees, multiply radians by 180/pi.
The following example uses Atn to calculate the value of pi:
Dim pi
pi = 4 * Atn(1)   ' Calculate the value of pi.
Note   Atn is the inverse trigonometric function of Tan, which takes an angle as its argument and returns the ratio of two sides of a right triangle. Do not confuse Atn with the cotangent, which is the simple inverse of a tangent (1/tangent).

CBool Function

Returns an expression that has been converted to a Variant of subtype Boolean.
CBool(expression)
The expression argument is any valid expression.

Remarks

If expression is zero, False is returned; otherwise, True is returned. If expression can't be interpreted as a numeric value, a run-time error occurs.
The following example uses the CBool function to convert an expression to a Boolean. If the expression evaluates to a nonzero value, CBool returns True; otherwise, it returns False.
Dim A, B, Check
A = 5: B = 5           ' Initialize variables.
Check = CBool(A = B)   ' Check contains True.
A = 0                  ' Define variable.
Check = CBool(A)       ' Check contains False.

CByte Function

Returns an expression that has been converted to a Variant of subtype Byte.
CByte(expression)
The expression argument is any valid expression.

Remarks

In general, you can document your code using the subtype conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CByte to force byte arithmetic in cases where currency, single-precision, double-precision, or integer arithmetic normally would occur.
Use the CByte function to provide internationally aware conversions from any other data type to a Byte subtype. For example, different decimal separators are properly recognized depending on the locale setting of your system, as are different thousand separators.
If expression lies outside the acceptable range for the byte subtype, an error occurs. The following example uses the CByte function to convert an expression to a byte:
Dim MyDouble, MyByte
MyDouble = 125.5678        ' MyDouble is a Double.
MyByte = CByte(MyDouble)   ' MyByte contains 126.

CCur Function

Returns an expression that has been converted to a Variant of subtype Currency.
CCur(expression)
The expression argument is any valid expression.

Remarks

In general, you can document your code using the subtype conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CCur to force currency arithmetic in cases where integer arithmetic normally would occur.
You should use the CCur function to provide internationally aware conversions from any other data type to a Currency subtype. For example, different decimal separators and thousands separators are properly recognized depending on the locale setting of your system.
The following example uses the CCur function to convert an expression to a Currency:
Dim MyDouble, MyCurr
MyDouble = 543.214588         ' MyDouble is a Double.
MyCurr = CCur(MyDouble * 2)   ' Convert result of MyDouble * 2 (1086.429176) to a Currency (1086.4292).

CDate Function

Returns an expression that has been converted to a Variant of subtype Date.
CDate(date)
The date argument is any valid date expression.

Remarks

Use the IsDate function to determine if date can be converted to a date or time. CDate recognizes date literals and time literals as well as some numbers that fall within the range of acceptable dates. When converting a number to a date, the whole number portion is converted to a date. Any fractional part of the number is converted to a time of day, starting at midnight.
CDate recognizes date formats according to the locale setting of your system. The correct order of day, month, and year may not be determined if it is provided in a format other than one of the recognized date settings. In addition, a long date format is not recognized if it also contains the day-of-the-week string.
The following example uses the CDate function to convert a string to a date. In general, hard coding dates and times as strings (as shown in this example) is not recommended. Use date and time literals (such as #10/19/1962#, #4:45:23 PM#) instead.
MyDate = "October 19, 1962"   ' Define date.
MyShortDate = CDate(MyDate)   ' Convert to Date data type.
MyTime = "4:35:47 PM"         ' Define time.
MyShortTime = CDate(MyTime)   ' Convert to Date data type.

CDbl Function

Returns an expression that has been converted to a Variant of subtype Double.
CDbl(expression)
The expression argument is any valid expression.

Remarks

In general, you can document your code using the subtype conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CDbl or CSng to force double-precision or single-precision arithmetic in cases where currency or integer arithmetic normally would occur.
Use the CDbl function to provide internationally aware conversions from any other data type to a Double subtype. For example, different decimal separators and thousands separators are properly recognized depending on the locale setting of your system.
This example uses the CDbl function to convert an expression to a Double.
Dim MyCurr, MyDouble
MyCurr = CCur(234.456784)              ' MyCurr is a Currency (234.4567).
MyDouble = CDbl(MyCurr * 8.2 * 0.01)   ' Convert result to a Double (19.2254576).

Chr Function

Returns the character associated with the specified ANSI character code.
Chr(charcode)
The charcode argument is a number that identifies a character.

Remarks

Numbers from 0 to 31 are the same as standard, nonprintable ASCII codes. For example, Chr(10) returns a linefeed character.
The following example uses the Chr function to return the character associated with the specified character code:
Dim MyChar
MyChar = Chr(65)   ' Returns A.
MyChar = Chr(97)   ' Returns a.
MyChar = Chr(62)   ' Returns >.
MyChar = Chr(37)   ' Returns %.
Note   The ChrB function is used with byte data contained in a string. Instead of returning a character, which may be one or two bytes, ChrB always returns a single byte. ChrW is provided for 32-bit platforms that use Unicode characters. Its argument is a Unicode (wide) character code, thereby avoiding the conversion from ANSI to Unicode.

CInt Function

Returns an expression that has been converted to a Variant of subtype Integer.
CInt(expression)
The expression argument is any valid expression.

Remarks

In general, you can document your code using the subtype conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CInt or CLng to force integer arithmetic in cases where currency, single-precision, or double-precision arithmetic normally would occur.
Use the CInt function to provide internationally aware conversions from any other data type to an Integer subtype. For example, different decimal separators are properly recognized depending on the locale setting of your system, as are different thousand separators.
If expression lies outside the acceptable range for the Integer subtype, an error occurs.
The following example uses the CInt function to convert a value to an Integer:
Dim MyDouble, MyInt
MyDouble = 2345.5678     ' MyDouble is a Double.
MyInt = CInt(MyDouble)   ' MyInt contains 2346.
Note   CInt differs from the Fix and Int functions, which truncate, rather than round, the fractional part of a number. When the fractional part is exactly 0.5, the CInt function always rounds it to the nearest even number. For example, 0.5 rounds to 0, and 1.5 rounds to 2.

CLng Function

Returns an expression that has been converted to a Variant of subtype Long.
CLng(expression)
The expression argument is any valid expression.

Remarks

In general, you can document your code using the subtype conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CInt or CLng to force integer arithmetic in cases where currency, single-precision, or double-precision arithmetic normally would occur.
Use the CLng function to provide internationally aware conversions from any other data type to a Long subtype. For example, different decimal separators are properly recognized depending on the locale setting of your system, as are different thousand separators.
If expression lies outside the acceptable range for the Long subtype, an error occurs.
The following example uses the CLng function to convert a value to a Long:
Dim MyVal1, MyVal2, MyLong1, MyLong2
MyVal1 = 25427.45: MyVal2 = 25427.55   ' MyVal1, MyVal2 are Doubles.
MyLong1 = CLng(MyVal1)   ' MyLong1 contains 25427.
MyLong2 = CLng(MyVal2)   ' MyLong2 contains 25428.
 
Note   CLng differs from the Fix and Int functions, which truncate, rather than round, the fractional part of a number. When the fractional part is exactly 0.5, the CLng function always rounds it to the nearest even number. For example, 0.5 rounds to 0, and 1.5 rounds to 2.

Cos Function

Returns the cosine of an angle.
Cos(number)
The number argument can be any valid numeric expression that expresses an angle in radians.

Remarks

The Cos function takes an angle and returns the ratio of two sides of a right triangle. The ratio is the length of the side adjacent to the angle divided by the length of the hypotenuse. The result lies in the range -1 to 1.
To convert degrees to radians, multiply degrees by pi /180. To convert radians to degrees, multiply radians by 180/pi.
The following example uses the Cos function to return the cosine of an angle:
Dim MyAngle, MySecant
MyAngle = 1.3                 ' Define angle in radians.
MySecant = 1 / Cos(MyAngle)   ' Calculate secant.

CreateObject Function

Creates and returns a reference to an Automation object.
CreateObject(servername.typename [, 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

Automation servers provide at least one type of object. For example, a word-processing application may provide an application object, a document object, and a toolbar object.
To create an Automation object, assign the object returned by CreateObject to an object variable:
Dim ExcelSheet
Set ExcelSheet = CreateObject("Excel.Sheet")
This code starts the application that creates the object (in this case, a 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 variable, ExcelSheet, and other Excel objects, including the Application object and 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 portion of a share name. For a network share named "\\myserver\public", the servername 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", "MyServer")
   GetVersion = XLApp.Version
End Function
An error occurs if the specified remote server does not exist or cannot be found.

CreateObject Method

Creates a COM object.
object.CreateObject(strProgID[,strPrefix]) 

Arguments

object
WScript object.
strProgID
String value indicating the programmatic identifier (ProgID) of the object you want to create.
strPrefix
Optional. String value indicating the function prefix.

Remarks

Objects created with the CreateObject method using the strPrefix argument are connected objects. These are useful when you want to sync an object's events. The object's outgoing interface is connected to the script file after the object is created. Event functions are a combination of this prefix and the event name. If you create an object and do not supply the strPrefix argument, you can still sync events on the object by using the ConnectObject method. When the object fires an event, WSH calls a subroutine with strPrefix attached to the beginning of the event name. For example, if strPrefix is MYOBJ and the object fires an event named OnBegin, Windows Script Host calls the MYOBJ_OnBegin subroutine located in the script. The CreateObject method returns a pointer to the object's IDispatch interface.

Example

The following VBScript code uses the CreateObject method to create a WshNetwork object:
Set WshNetwork = WScript.CreateObject("WScript.Network")

CSng Function

Returns an expression that has been converted to a Variant of subtype Single.
CSng(expression) 
The expression argument is any valid expression.

Remarks

In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CDbl or CSng to force double-precision or single-precision arithmetic in cases where currency or integer arithmetic normally would occur.
Use the CSng function to provide internationally aware conversions from any other data type to a Single subtype. For example, different decimal separators are properly recognized depending on the locale setting of your system, as are different thousand separators.
If expression lies outside the acceptable range for the Single subtype, an error occurs.
The following example uses the CSng function to convert a value to a Single:
Dim MyDouble1, MyDouble2, MySingle1, MySingle2   ' MyDouble1, MyDouble2 are Doubles.
MyDouble1 = 75.3421115: MyDouble2 = 75.3421555
MySingle1 = CSng(MyDouble1)   ' MySingle1 contains 75.34211.
MySingle2 = CSng(MyDouble2)   ' MySingle2 contains 75.34216.

CStr Function

Returns an expression that has been converted to a Variant of subtype String.
CStr(expression)
The expression argument is any valid expression.

Remarks

In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CStr to force the result to be expressed as a String.
You should use the CStr function instead of Str to provide internationally aware conversions from any other data type to a String subtype. For example, different decimal separators are properly recognized depending on the locale setting of your system.
The data in expression determines what is returned according to the following table:
If expression is
CStr returns
Boolean
A String containing True or False.
Date
A String containing a date in the short-date format of your system.
Null
A run-time error.
Empty
A zero-length String ("").
Error
A String containing the word Error followed by the error number.
Other numeric
A String containing the number.
The following example uses the CStr function to convert a numeric value to a String:
Dim MyDouble, MyString
MyDouble = 437.324         ' MyDouble is a Double.
MyString = CStr(MyDouble)   ' MyString contains "437.324".

Date Function

Returns the current system date.
Date

Remarks

The following example uses the Date function to return the current system date:
Dim MyDate
MyDate = Date   ' MyDate contains the current system date.

Date and Time Constants

Since these constants are built into VBScript, you don't have to define them before using them. Use them anywhere in your code to represent the values shown for each.
Constant
Value
Description
vbSunday
1
Sunday
vbMonday
2
Monday
vbTuesday
3
Tuesday
vbWednesday
4
Wednesday
vbThursday
5
Thursday
vbFriday
6
Friday
vbSaturday
7
Saturday
vbUseSystemDayOfWeek
0
Use the day of the week specified in your system settings for the first day of the week.
vbFirstJan1
1
Use the week in which January 1 occurs (default).
vbFirstFourDays
2
Use the first week that has at least four days in the new year.
vbFirstFullWeek
3
Use the first full week of the year.

TypeName Function

Returns a string that provides Variant subtype information about a variable.
TypeName(varname)
The required varname argument can be any variable.

Return Values

The TypeName function has the following return values:
Value
Description
Byte
Byte value
Integer
Integer value
Long
Long integer value
Single
Single-precision floating-point value
Double
Double-precision floating-point value
Currency
Currency value
Decimal
Decimal value
Date
Date or time value
String
Character string value
Boolean
Boolean value; True or False
Empty
Unitialized
Null
No valid data

Actual type name of an object
Object
Generic object
Unknown
Unknown object type
Nothing
Object variable that doesn't yet refer to an object instance
Error
Error

DateAdd Function

Returns a date to which a specified time interval has been added.
DateAdd(interval, number, date)

Arguments

interval
Required. String expression that is the interval you want to add. See Settings section for values.
number
Required. Numeric expression that is the number of interval you want to add. The numeric expression can either be positive, for dates in the future, or negative, for dates in the past.
date
Required. Variant or literal representing the date to which interval is added.

Settings

The interval argument can have the following values:
Setting
Description
yyyy
Year
q
Quarter
m
Month
y
Day of year
d
Day
w
Weekday
ww
Week of year
h
Hour
n
Minute
s
Second

Remarks

You can use the DateAdd function to add or subtract a specified time interval from a date. For example, you can use DateAdd to calculate a date 30 days from today or a time 45 minutes from now. To add days to date, you can use Day of Year ("y"), Day ("d"), or Weekday ("w").
The DateAdd function won't return an invalid date. The following example adds one month to January 31:
NewDate = DateAdd("m", 1, "31-Jan-95")
In this case, DateAdd returns 28-Feb-95, not 31-Feb-95. If date is 31-Jan-96, it returns 29-Feb-96 because 1996 is a leap year.
If the calculated date would precede the year 100, an error occurs.
If number isn't a Long value, it is rounded to the nearest whole number before being evaluated.

DateDiff Function

Returns the number of intervals between two dates.
DateDiff(interval, date1, date2 [,firstdayofweek[, firstweekofyear]])
The DateDiff function syntax has these parts:

Arguments

interval
Required. String expression that is the interval you want to use to calculate the differences between date1 and date2. See Settings section for values.
date1, date2
Required. Date expressions. Two dates you want to use in the calculation.
firstdayofweek
Optional. Constant that specifies the day of the week. If not specified, Sunday is assumed. See Settings section for values.
firstweekofyear
Optional. Constant that specifies the first week of the year. If not specified, the first week is assumed to be the week in which January 1 occurs. See Settings section for values.

Settings

The interval argument can have the following values:
Setting
Description
yyyy
Year
q
Quarter
m
Month
y
Day of year
d
Day
w
Weekday
ww
Week of year
h
Hour
n
Minute
s
Second
The firstdayofweek argument can have the following values:
Constant
Value
Description
vbUseSystemDayOfWeek
0
Use National Language Support (NLS) API setting.
vbSunday
1
Sunday (default)
vbMonday
2
Monday
vbTuesday
3
Tuesday
vbWednesday
4
Wednesday
vbThursday
5
Thursday
vbFriday
6
Friday
vbSaturday
7
Saturday
The firstweekofyear argument can have the following values:
Constant
Value
Description
vbUseSystem
0
Use National Language Support (NLS) API setting.
vbFirstJan1
1
Start with the week in which January 1 occurs (default).
vbFirstFourDays
2
Start with the week that has at least four days in the new year.
vbFirstFullWeek
3
Start with the first full week of the new year.

Remarks

You can use the DateDiff function to determine how many specified time intervals exist between two dates. For example, you might use DateDiff to calculate the number of days between two dates, or the number of weeks between today and the end of the year.
To calculate the number of days between date1 and date2, you can use either Day of year ("y") or Day ("d"). When interval is Weekday ("w"), DateDiff returns the number of weeks between the two dates. If date1 falls on a Monday, DateDiff counts the number of Mondays until date2. It counts date2 but not date1. If interval is Week ("ww"), however, the DateDiff function returns the number of calendar weeks between the two dates. It counts the number of Sundays between date1 and date2. DateDiff counts date2 if it falls on a Sunday; but it doesn't count date1, even if it does fall on a Sunday.
If date1 refers to a later point in time than date2, the DateDiff function returns a negative number.
The firstdayofweek argument affects calculations that use the "w" and "ww" interval symbols.
If date1 or date2 is a date literal, the specified year becomes a permanent part of that date. However, if date1 or date2 is enclosed in quotation marks (" ") and you omit the year, the current year is inserted in your code each time the date1 or date2 expression is evaluated. This makes it possible to write code that can be used in different years.
When comparing December 31 to January 1 of the immediately succeeding year, DateDiff for Year ("yyyy") returns 1 even though only a day has elapsed.
The following example uses the DateDiff function to display the number of days between a given date and today:
Function DiffADate(theDate)
   DiffADate = "Days from today: " & DateDiff("d", Now, theDate)
End Function

DatePart Function

Returns the specified part of a given date.
DatePart(interval, date[, firstdayofweek[, firstweekofyear]])

Arguments

interval
Required. String expression that is the interval of time you want to return. See Settings section for values.
date
Required. Date expression you want to evaluate.
firstdayof week
Optional. Constant that specifies the day of the week. If not specified, Sunday is assumed. See Settings section for values.
firstweekofyear
Optional. Constant that specifies the first week of the year. If not specified, the first week is assumed to be the week in which January 1 occurs. See Settings section for values.

Settings

The interval argument can have the following values:
Setting
Description
yyyy
Year
q
Quarter
m
Month
y
Day of year
d
Day
w
Weekday
ww
Week of year
h
Hour
n
Minute
s
Second
The firstdayofweek argument can have the following values:
Constant
Value
Description
vbUseSystemDayOfWeek
0
Use National Language Support (NLS) API setting.
vbSunday
1
Sunday (default)
vbMonday
2
Monday
vbTuesday
3
Tuesday
vbWednesday
4
Wednesday
vbThursday
5
Thursday
vbFriday
6
Friday
vbSaturday
7
Saturday
The firstweekofyear argument can have the following values:
Constant
Value
Description
vbUseSystem
0
Use National Language Support (NLS) API setting.
vbFirstJan1
1
Start with the week in which January 1 occurs (default).
vbFirstFourDays
2
Start with the week that has at least four days in the new year.
vbFirstFullWeek
3
Start with the first full week of the new year.

Remarks

You can use the DatePart function to evaluate a date and return a specific interval of time. For example, you might use DatePart to calculate the day of the week or the current hour.
The firstdayofweek argument affects calculations that use the "w" and "ww" interval symbols.
If date is a date literal, the specified year becomes a permanent part of that date. However, if date is enclosed in quotation marks (" "), and you omit the year, the current year is inserted in your code each time the date expression is evaluated. This makes it possible to write code that can be used in different years.
This example takes a date and, using the DatePart function, displays the quarter of the year in which it occurs.
Function GetQuarter(TheDate)
   GetQuarter = DatePart("q", TheDate)
End Function

DateSerial Function

Returns a Variant of subtype Date for a specified year, month, and day.
DateSerial(year, month, day)

Arguments

year
Number between 100 and 9999, inclusive, or a numeric expression.
month
Any numeric expression.
day
Any numeric expression.

Remarks

To specify a date, such as December 31, 1991, the range of numbers for each DateSerial argument should be in the accepted range for the unit; that is, 1–31 for days and 1–12 for months. However, you can also specify relative dates for each argument using any numeric expression that represents some number of days, months, or years before or after a certain date.
The following example uses numeric expressions instead of absolute date numbers. Here the DateSerial function returns a date that is the day before the first day (1 – 1) of two months before August (8 – 2) of 10 years before 1990 (1990 – 10); in other words, May 31, 1980.
Dim MyDate1, MyDate2
MyDate1 = DateSerial(1970, 1, 1)   ' Returns January 1, 1970.
MyDate2 = DateSerial(1990 - 10, 8 - 2, 1 - 1)   ' Returns May 31, 1980.
For the year argument, values between 0 and 99, inclusive, are interpreted as the years 1900–1999. For all other year arguments, use a complete four-digit year (for example, 1800).
When any argument exceeds the accepted range for that argument, it increments to the next larger unit as appropriate. For example, if you specify 35 days, it is evaluated as one month and some number of days, depending on where in the year it is applied. However, if any single argument is outside the range -32,768 to 32,767, or if the date specified by the three arguments, either directly or by expression, falls outside the acceptable range of dates, an error occurs.

DateValue Function

Returns a Variant of subtype Date.
DateValue(date)
The date argument is normally a string expression representing a date from January 1, 100 through December 31, 9999. However, date can also be any expression that can represent a date, a time, or both a date and time, in that range.

Remarks

If the date argument includes time information, DateValue doesn't return it. However, if date includes invalid time information (such as "89:98"), an error occurs.
If date is a string that includes only numbers separated by valid date separators, DateValue recognizes the order for month, day, and year according to the short date format you specified for your system. DateValue also recognizes unambiguous dates that contain month names, either in long or abbreviated form. For example, in addition to recognizing 12/30/1991 and 12/30/91, DateValue also recognizes December 30, 1991 and Dec 30, 1991.
If the year part of date is omitted, DateValue uses the current year from your computer's system date.
The following example uses the DateValue function to convert a string to a date. You can also use date literals to directly assign a date to a Variant variable, for example, MyDate = #9/11/63#.
Dim MyDate
MyDate = DateValue("September 11, 1963")   ' Return a date.

Day Function

Returns a whole number between 1 and 31, inclusive, representing the day of the month.
Day(date)
The date argument is any expression that can represent a date. If date contains Null, Null is returned.
The following example uses the Day function to obtain the day of the month from a specified date:
Dim MyDay
MyDay = Day("October 19, 1962")   ' MyDay contains 19.

Weekday Function

Returns a whole number representing the day of the week.
Weekday(date, [firstdayofweek])

Arguments

date
Any expression that can represent a date. If date contains Null, Null is returned.
firstdayofweek
A constant that specifies the first day of the week. If omitted, vbSunday is assumed.

Settings

The firstdayofweek argument has these settings:
Constant
Value
Description
vbUseSystemDayOfWeek
0
Use National Language Support (NLS) API setting.
vbSunday
1
Sunday
vbMonday
2
Monday
vbTuesday
3
Tuesday
vbWednesday
4
Wednesday
vbThursday
5
Thursday
vbFriday
6
Friday
vbSaturday
7
Saturday

Return Values

The Weekday function can return any of these values:
Constant
Value
Description
vbSunday
1
Sunday
vbMonday
2
Monday
vbTuesday
3
Tuesday
vbWednesday
4
Wednesday
vbThursday
5
Thursday
vbFriday
6
Friday
vbSaturday
7
Saturday

Remarks

The following example uses the Weekday function to obtain the day of the week from a specified date:
Dim MyDate, MyWeekDay
MyDate = #October 19, 1962#   ' Assign a date.
MyWeekDay = Weekday(MyDate)   ' MyWeekDay contains 6 because MyDate represents a Friday.

DescribeResult Statement

Description :- Returns a text description of the last error.
Syntax :-                 DescribeResult(Error)
Argument
Type
Description
Error
Integer
The error.
Return Value
String
Example
In the following example, the script fails to run successfully because the image Login was not found on the Mercury Tours page. Using the DescribeResult function, a description of the error is placed into a message box.
Browser("Mercury Tours").Page("Mercury Tours").Image("Login").Click 19, 55
x = GetLastError
msgbox(DescribeResult(x))

Eval

Evaluates an expression and returns the result.
[result = ]Eval(expression)

Arguments

result
Optional. Variable to which return value assignment is made. If result is not specified, consider using the Execute statement instead.
expression
Required. String containing any legal VBScript expression.

Remarks

In VBScript, x = y can be interpreted two ways. The first is as an assignment statement, where the value of y is assigned to x. The second interpretation is as an expression that tests if x and y have the same value. If they do, result is True; if they are not, result is False. The Eval method always uses the second interpretation, whereas the Execute statement always uses the first.
Note   In Microsoft® JScript™, no confusion exists between assignment and comparison, because the assignment operator (=) is different from the comparison operator (==).
The following example illustrates the use of the Eval function:
Sub GuessANumber
   Dim Guess, RndNum
   RndNum = Int((100) * Rnd(1) + 1)
   Guess = CInt(InputBox("Enter your guess:",,0))
   Do
      If Eval("Guess = RndNum") Then
         MsgBox "Congratulations! You guessed it!"
         Exit Sub
      Else
         Guess = CInt(InputBox("Sorry! Try again.",,0))
      End If
   Loop Until Guess = 0
End Sub

Exp Function

Returns e (the base of natural logarithms) raised to a power.
Exp(number)
The number argument can be any valid numeric expression.

Remarks

If the value of number exceeds 709.782712893, an error occurs. The constant e is approximately 2.718282.
Note   The Exp function complements the action of the Log function and is sometimes referred to as the antilogarithm.
The following example uses the Exp function to return e raised to a power:
Dim MyAngle, MyHSin   ' Define angle in radians.
MyAngle = 1.3   ' Calculate hyperbolic sine.
MyHSin = (Exp(MyAngle) - Exp(-1 * MyAngle)) / 2 

Filter Function

Returns a zero-based array containing a subset of a string array based on a specified filter criteria.
Filter(InputStrings, Value[, Include[, Compare]])

Arguments

InputStrings
Required. One-dimensional array of strings to be searched.
Value
Required. String to search for.
Include
Optional. Boolean value indicating whether to return substrings that include or exclude Value. If Include is True, Filter returns the subset of the array that contains Value as a substring. If Include is False, Filter returns the subset of the array that does not contain Value as a substring.
Compare
Optional. Numeric value indicating the kind of string comparison to use. See Settings section for values.

Settings

The Compare argument can have the following values:
Constant
Value
Description
vbBinaryCompare
0
Perform a binary comparison.
vbTextCompare
1
Perform a textual comparison.

Remarks

If no matches of Value are found within InputStrings, Filter returns an empty array. An error occurs if InputStrings is Null or is not a one-dimensional array.
The array returned by the Filter function contains only enough elements to contain the number of matched items.
The following example uses the Filter function to return the array containing the search criteria "Mon":
Dim MyIndex
Dim MyArray (3)
MyArray(0) = "Sunday"
MyArray(1) = "Monday"
MyArray(2) = "Tuesday"
MyIndex = Filter(MyArray, "Mon") ' MyIndex(0) contains "Monday".

Int, Fix Functions

Returns the integer portion of a number.
Int(number)
Fix(number)
The number argument can be any valid numeric expression. If number contains Null, Null is returned.

Remarks

Both Int and Fix remove the fractional part of number and return the resulting integer value.
The difference between Int and Fix is that if number is negative, Int returns the first negative integer less than or equal to number, whereas Fix returns the first negative integer greater than or equal to number. For example, Int converts -8.4 to -9, and Fix converts -8.4 to -8.
Fix(number) is equivalent to:
Sgn(number) * Int(Abs(number))
The following examples illustrate how the Int and Fix functions return integer portions of numbers:
MyNumber = Int(99.8)    ' Returns 99.
MyNumber = Fix(99.2)    ' Returns 99.
MyNumber = Int(-99.8)   ' Returns -100.
MyNumber = Fix(-99.8)   ' Returns -99.
MyNumber = Int(-99.2)   ' Returns -100.
MyNumber = Fix(-99.2)   ' Returns -99.

FormatCurrency Function

Returns an expression formatted as a currency value using the currency symbol defined in the system control panel.
FormatCurrency(Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit [,UseParensForNegativeNumbers [,GroupDigits]]]]) 

Arguments

Expression
Required. Expression to be formatted.
NumDigitsAfterDecimal
Optional. Numeric value indicating how many places to the right of the decimal are displayed. Default value is -1, which indicates that the computer's regional settings are used.
IncludeLeadingDigit
Optional. Tristate constant that indicates whether or not a leading zero is displayed for fractional values. See Settings section for values.
UseParensForNegativeNumbers
Optional. Tristate constant that indicates whether or not to place negative values within parentheses. See Settings section for values.
GroupDigits
Optional. Tristate constant that indicates whether or not numbers are grouped using the group delimiter specified in the computer's regional settings. See Settings section for values.

Settings

The IncludeLeadingDigit, UseParensForNegativeNumbers, and GroupDigits arguments have the following settings:
Constant
Value
Description
TristateTrue
-1
True
TristateFalse
0
False
TristateUseDefault
-2
Use the setting from the computer's regional settings.

Remarks

When one or more optional arguments are omitted, values for omitted arguments are provided by the computer's regional settings. The position of the currency symbol relative to the currency value is determined by the system's regional settings.
Note   All settings information comes from the Regional Settings Currency tab, except leading zero, which comes from the Number tab.
The following example uses the FormatCurrency function to format the expression as a currency and assign it to MyCurrency:
Dim MyCurrency
MyCurrency = FormatCurrency(1000)   ' MyCurrency contains $1000.00.

FormatDateTime Function

Returns an expression formatted as a date or time.
FormatDateTime(Date[, NamedFormat])

Arguments

Date
Required. Date expression to be formatted.
NamedFormat
Optional. Numeric value that indicates the date/time format used. If omitted, vbGeneralDate is used.

Settings

The NamedFormat argument has the following settings:
Constant
Value
Description

vbGeneralDate
0
Display a date and/or time. If there is a date part, display it as a short date. If there is a time part, display it as a long time. If present, both parts are displayed.
vbLongDate
1
Display a date using the long date format specified in your computer's regional settings.
vbShortDate
2
Display a date using the short date format specified in your computer's regional settings.
vbLongTime
3
Display a time using the time format specified in your computer's regional settings.
vbShortTime
4
Display a time using the 24-hour format (hh:mm).

Remarks

The following example uses the FormatDateTime function to format the expression as a long date and assign it to MyDateTime:
Function GetCurrentDate
   ' FormatDateTime formats Date in long date. 
   GetCurrentDate = FormatDateTime(Date, 1) 
End Function

FormatNumber Function

Returns an expression formatted as a number.
FormatNumber(Expression [,NumDigitsAfterDecimal [,IncludeLeadingDigit [,UseParensForNegativeNumbers [,GroupDigits]]]])

Arguments

Expression
Required. Expression to be formatted.
NumDigitsAfterDecimal
Optional. Numeric value indicating how many places to the right of the decimal are displayed. Default value is -1, which indicates that the computer's regional settings are used.
IncludeLeadingDigit
Optional. Tristate constant that indicates whether or not a leading zero is displayed for fractional values. See Settings section for values.
UseParensForNegativeNumbers
Optional. Tristate constant that indicates whether or not to place negative values within parentheses. See Settings section for values.
GroupDigits
Optional. Tristate constant that indicates whether or not numbers are grouped using the group delimiter specified in the control panel. See Settings section for values.

Settings

The IncludeLeadingDigit, UseParensForNegativeNumbers, and GroupDigits arguments have the following settings:
Constant
Value
Description
TristateTrue
-1
True
TristateFalse
0
False
TristateUseDefault
-2
Use the setting from the computer's regional settings.

Remarks

When one or more of the optional arguments are omitted, the values for omitted arguments are provided by the computer's regional settings.
Note   All settings information comes from the Regional Settings Number tab.
The following example uses the FormatNumber function to format a number to have four decimal places:
Function FormatNumberDemo
   Dim MyAngle, MySecant, MyNumber
   MyAngle = 1.3   ' Define angle in radians.
   MySecant = 1 / Cos(MyAngle)   ' Calculate secant.
   FormatNumberDemo = FormatNumber(MySecant,4) ' Format MySecant to four decimal places.
End Function

FormatPercent Function

Returns an expression formatted as a percentage (multiplied by 100) with a trailing % character.
FormatPercent(Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit [,UseParensForNegativeNumbers [,GroupDigits]]]])
The FormatPercent function syntax has these parts:

Arguments

Expression
Required. Expression to be formatted.
NumDigitsAfterDecimal
Optional. Numeric value indicating how many places to the right of the decimal are displayed. Default value is -1, which indicates that the computer's regional settings are used.
IncludeLeadingDigit
Optional. Tristate constant that indicates whether or not a leading zero is displayed for fractional values. See Settings section for values.
UseParensForNegativeNumbers
Optional. Tristate constant that indicates whether or not to place negative values within parentheses. See Settings section for values.
GroupDigits
Optional. Tristate constant that indicates whether or not numbers are grouped using the group delimiter specified in the control panel. See Settings section for values.

Settings

The IncludeLeadingDigit, UseParensForNegativeNumbers, and GroupDigits arguments have the following settings:
Constant
Value
Description
TristateTrue
-1
True
TristateFalse
0
False
TristateUseDefault
-2
Use the setting from the computer's regional settings.

Remarks

When one or more optional arguments are omitted, the values for the omitted arguments are provided by the computer's regional settings.
Note   All settings information comes from the Regional Settings Number tab.
The following example uses the FormatPercent function to format an expression as a percent:
Dim MyPercent
MyPercent = FormatPercent(2/32) ' MyPercent contains 6.25%.

FormatDateTime Function

Returns an expression formatted as a date or time.
FormatDateTime(Date[, NamedFormat])

Arguments

Date
Required. Date expression to be formatted.
NamedFormat
Optional. Numeric value that indicates the date/time format used. If omitted, vbGeneralDate is used.

Settings

The NamedFormat argument has the following settings:
Constant
Value
Description
vbGeneralDate
0
Display a date and/or time. If there is a date part, display it as a short date. If there is a time part, display it as a long time. If present, both parts are displayed.
vbLongDate
1
Display a date using the long date format specified in your computer's regional settings.
vbShortDate
2
Display a date using the short date format specified in your computer's regional settings.
vbLongTime
3
Display a time using the time format specified in your computer's regional settings.
vbShortTime
4
Display a time using the 24-hour format (hh:mm).

Remarks

The following example uses the FormatDateTime function to format the expression as a long date and assign it to MyDateTime:
Function GetCurrentDate
   ' FormatDateTime formats Date in long date. 
   GetCurrentDate = FormatDateTime(Date, 1) 
End Function

GetLastError Statement

Description
Returns the error code of the most recent error. You can use this statement together with the DescribeResult Statement.
Syntax
GetLastError
Return Value
Number
Example
In the following example, the script fails to run successfully because the Login image was not found on the Mercury Tours page. Using the GetLastError function, the error number and description are inserted into a message box.
Browser("Mercury Tours").Page("Mercury Tours").Image("Login").Click 19, 55
x = GetLastError
msgbox(DescribeResult(x))

GetLocale Function

Returns the current locale ID value.
GetLocale()

Remarks

A locale is a set of user preference information related to the user's language, country/region, and cultural conventions. The locale determines such things as keyboard layout, alphabetic sort order, as well as date, time, number, and currency formats.
The return value can be any of the 32-bit values shown in the Locale ID chart:
The following example illustrates the use of the GetLocale function. To use this code, paste the entire example between the tags of a standard HTML page.
Enter Date in UK format: 
Here's the US equivalent: 
Enter a price in German:   
Here's the UK equivalent: 
 
 

GetObject Function

Returns a reference to an Automation object from a file.
GetObject([pathname] [, class])

Arguments

pathname
Optional; String. Full path and name of the file containing the object to retrieve. If pathname is omitted, class is required.
class
Optional; String. Class of the object.
The class argument uses the syntax appname.objectype and has these parts:

Arguments

appname
Required; String. Name of the application providing the object.
objectype
Required; String. Type or class of object to create.

Remarks

Use the GetObject function to access an Automation object from a file and assign the object to an object variable. Use the Set statement to assign the object returned by GetObject to the object variable. For example:
Dim CADObject
Set CADObject = GetObject("C:\CAD\SCHEMA.CAD")
When this code is executed, the application associated with the specified pathname is started and the object in the specified file is activated. If pathname is a zero-length string (""), GetObject returns a new object instance of the specified type. If the pathname argument is omitted, GetObject returns a currently active object of the specified type. If no object of the specified type exists, an error occurs.
Some applications allow you to activate part of a file. Add an exclamation point (!) to the end of the file name and follow it with a string that identifies the part of the file you want to activate. For information on how to create this string, see the documentation for the application that created the object.
For example, in a drawing application you might have multiple layers to a drawing stored in a file. You could use the following code to activate a layer within a drawing called SCHEMA.CAD:
Set LayerObject = GetObject("C:\CAD\SCHEMA.CAD!Layer3")
If you don't specify the object's class, Automation determines the application to start and the object to activate, based on the file name you provide. Some files, however, may support more than one class of object. For example, a drawing might support three different types of objects: an Application object, a Drawing object, and a Toolbar object, all of which are part of the same file. To specify which object in a file you want to activate, use the optional class argument. For example:
Dim MyObject
Set MyObject = GetObject("C:\DRAWINGS\SAMPLE.DRW", "FIGMENT.DRAWING")
In the preceding example, FIGMENT is the name of a drawing application and DRAWING is one of the object types it supports. Once an object is activated, you reference it in code using the object variable you defined. In the preceding example, you access properties and methods of the new object using the object variable MyObject. For example:
MyObject.Line 9, 90
MyObject.InsertText 9, 100, "Hello, world."
MyObject.SaveAs "C:\DRAWINGS\SAMPLE.DRW"
Note   Use the GetObject function when there is a current instance of the object or if you want to create the object with a file already loaded. If there is no current instance, and you don't want the object started with a file loaded, use the CreateObject function.
If an object has registered itself as a single-instance object, only one instance of the object is created, no matter how many times CreateObject is executed. With a single-instance object, GetObject always returns the same instance when called with the zero-length string ("") syntax, and it causes an error if the pathname argument is omitted.

GetObject Method

Retrieves an existing object with the specified ProgID, or creates a new one from a file.
object.GetObject(strPathname [,strProgID], [strPrefix]) 

Arguments

object
WScript object.
strPathname
The fully qualified path name of the file that contains the object persisted to disk.
strProgID
Optional. The object's program identifier (ProgID).
strPrefix
Optional. Used when you want to sync the object's events. If you supply the strPrefix argument, WSH connects the object's outgoing interface to the script file after creating the object.

Remarks

Use the GetObject method when an instance of the object exists in memory, or when you want to create the object from a file. If no current instance exists and you do not want the object created from a file, use the CreateObject method. The GetObject method can be used with all COM classes, independent of the language used to create the object. If you supply the strPrefix argument, WSH connects the object's outgoing interface to the script file after creating the object. When the object fires an event, WSH calls a subroutine with strPrefix attached to the beginning of the event name. For example, if strPrefix is MYOBJ_ and the object fires an event named OnBegin, WSH calls the MYOBJ_OnBegin subroutine located in the script.
If an object is registered as a single-instance object, only one instance of the object is created (regardless of how many times GetObject is executed). The GetObject method always returns the same instance when called with the zero-length string syntax (""), and it causes an error if you do not supply the path parameter. You cannot use the GetObject method to obtain a reference to a Microsoft Visual Basic class created with Visual Basic 4.0 or earlier.

Example

The following VBScript code starts the application associated with the specified file (strPathname):
Dim MyObject As Object
Set MyObject = GetObject("C:\CAD\SCHEMA.CAD")
MyApp = MyObject.Application
Some applications allow you to activate part of a file. To do this, add an exclamation mark (!) to the end of the file name, and follow it with a string that identifies the part of the file you want to activate. For example, in a drawing application, a drawing stored in a file might have multiple layers. The following code activates a layer within a drawing file called SCHEMA.CAD:
Set LayerObject = GetObject("C:\CAD\SCHEMA.CAD!Layer3")
If you do not specify the object's class (strProgID), COM determines the application to start from the file name. Some files can support more than one class of object. For example, a drawing might support three different types of objects: an application object, a drawing object, and a toolbar object. All may be part of the same file.
In the following VBScript code, the drawing application FIGMENT starts and opens the object DRAWING from within the file SAMPLE.DRW.
Dim MyObject As Object
Set MyObject = GetObject("C:\DRAWINGS\SAMPLE.DRW", "FIGMENT.DRAWING")

GetRef Function

Returns a reference to a procedure that can be bound to an event.
Set object.eventname = GetRef(procname)

Arguments

object
Required. Name of the object with which event is associated.
event
Required. Name of the event to which the function is to be bound.
procname
Required. String containing the name of the Sub or Function procedure being associated with the event.

Remarks

The GetRef function allows you to connect a VBScript procedure (Function or Sub) to any available event on your DHTML (Dynamic HTML) pages. The DHTML object model provides information about what events are available for its various objects.
In other scripting and programming languages, the functionality provided by GetRef is referred to as a function pointer, that is, it points to the address of a procedure to be executed when the specified event occurs.
The following example illustrates the use of the GetRef function.

Hex Function

Returns a string representing the hexadecimal value of a number.
Hex(number)
The number argument is any valid expression.

Remarks

If number is not already a whole number, it is rounded to the nearest whole number before being evaluated.
If number is
Hex returns
Null
Null.
Empty
Zero (0).
Any other number
Up to eight hexadecimal characters.
You can represent hexadecimal numbers directly by preceding numbers in the proper range with &H. For example, &H10 represents decimal 16 in hexadecimal notation.
The following example uses the Hex function to return the hexadecimal value of a number:
Dim MyHex
MyHex = Hex(5)   ' Returns 5.
MyHex = Hex(10)   ' Returns A.
MyHex = Hex(459)   ' Returns 1CB.

Hour Function

Returns a whole number between 0 and 23, inclusive, representing the hour of the day.
Hour(time)
The time argument is any expression that can represent a time. If time contains Null, Null is returned.
The following example uses the Hour function to obtain the hour from the current time:
Dim MyTime, MyHour
MyTime = Now
MyHour = Hour(MyTime) ' MyHour contains the number representing 
                      ' the current hour.

InputBox Function

Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns the contents of the text box.
InputBox(prompt[, title][, default][, xpos][, ypos][, helpfile, context])

Arguments

prompt
String expression displayed as the message in the dialog box. The maximum length of prompt is approximately 1024 characters, depending on the width of the characters used. If prompt consists of more than one line, you can separate the lines using a carriage return character (Chr(13)), a linefeed character (Chr(10)), or carriage return–linefeed character combination (Chr(13) & Chr(10)) between each line.
title
String expression displayed in the title bar of the dialog box. If you omit title, the application name is placed in the title bar.
default
String expression displayed in the text box as the default response if no other input is provided. If you omit default, the text box is displayed empty.
xpos
Numeric expression that specifies, in twips, the horizontal distance of the left edge of the dialog box from the left edge of the screen. If xpos is omitted, the dialog box is horizontally centered.
ypos
Numeric expression that specifies, in twips, the vertical distance of the upper edge of the dialog box from the top of the screen. If ypos is omitted, the dialog box is vertically positioned approximately one-third of the way down the screen.
helpfile
String expression that identifies the Help file to use to provide context-sensitive Help for the dialog box. If helpfile is provided, context must also be provided.
context
Numeric expression that identifies the Help context number assigned by the Help author to the appropriate Help topic. If context is provided, helpfile must also be provided.

Remarks

When both helpfile and context are supplied, a Help button is automatically added to the dialog box.
If the user clicks OK or presses ENTER, the InputBox function returns whatever is in the text box. If the user clicks Cancel, the function returns a zero-length string ("").
The following example uses the InputBox function to display an input box and assign the string to the variable Input:
Dim Input
Input = InputBox("Enter your name") 
MsgBox ("You entered: " & Input)

InStr Function

Returns the position of the first occurrence of one string within another.
InStr([start, ]string1, string2[, compare])

Arguments

start
Optional. Numeric expression that sets the starting position for each search. If omitted, search begins at the first character position. If start contains Null, an error occurs. The start argument is required if compare is specified.
string1
Required. String expression being searched.
string2
Required. String expression searched for.
compare
Optional. Numeric value indicating the kind of comparison to use when evaluating substrings. See Settings section for values. If omitted, a binary comparison is performed.

Settings

The compare argument can have the following values:
Constant
Value
Description
vbBinaryCompare
0
Perform a binary comparison.
vbTextCompare
1
Perform a textual comparison.

Return Values

The InStr function returns the following values:
If
InStr returns
string1 is zero-length
0
string1 is Null
Null
string2 is zero-length
start
string2 is Null
Null
string2 is not found
0
string2 is found within string1
Position at which match is found
start > Len(string2)
0

Remarks

The following examples use InStr to search a string:
Dim SearchString, SearchChar, MyPos
SearchString ="XXpXXpXXPXXP"   ' String to search in.
SearchChar = "P"   ' Search for "P".
MyPos = Instr(4, SearchString, SearchChar, 1)   ' A textual comparison starting at position 4. Returns 6.
MyPos = Instr(1, SearchString, SearchChar, 0)   ' A binary comparison starting at position 1. Returns 9.    
MyPos = Instr(SearchString, SearchChar)   ' Comparison is binary by default (last argument is omitted). Returns 9.
MyPos = Instr(1, SearchString, "W")   ' A binary comparison starting at position 1. Returns 0 ("W" is not found).
Note   The InStrB function is used with byte data contained in a string. Instead of returning the character position of the first occurrence of one string within another, InStrB returns the byte position.

InStrRev Function

Returns the position of an occurrence of one string within another, from the end of string.
InStrRev(string1, string2[, start[, compare]])

Arguments

string1
Required. String expression being searched.
string2
Required. String expression being searched for.
start
Optional. Numeric expression that sets the starting position for each search. If omitted, -1 is used, which means that the search begins at the last character position. If start contains Null, an error occurs.
compare
Optional. Numeric value indicating the kind of comparison to use when evaluating substrings. If omitted, a binary comparison is performed. See Settings section for values.

Settings

The compare argument can have the following values:
Constant
Value
Description
vbBinaryCompare
0
Perform a binary comparison.
vbTextCompare
1
Perform a textual comparison.

Return Values

InStrRev returns the following values:
If
InStrRev returns
string1 is zero-length
0
string1 is Null
Null
string2 is zero-length
start
string2 is Null
Null
string2 is not found
0
string2 is found within string1
Position at which match is found
start > Len(string2)
0

Remarks

The following examples use the InStrRev function to search a string:
Dim SearchString, SearchChar, MyPos
SearchString ="XXpXXpXXPXXP"   ' String to search in.
SearchChar = "P"   ' Search for "P".
MyPos = InstrRev(SearchString, SearchChar, 10, 0)   ' A binary comparison starting at position 10. Returns 9.
MyPos = InstrRev(SearchString, SearchChar, -1, 1)   ' A textual comparison starting at the last position. Returns 12.
MyPos = InstrRev(SearchString, SearchChar, 8)   ' Comparison is binary by default (last argument is omitted). Returns 0.
Note   The syntax for the InStrRev function is not the same as the syntax for the InStr function.

InvokeApplication Statement

Description
Invokes an executable application.
Note: In most situations, you should use a SystemUtil.Run statement to run applications or to open files in their default application. For more information on the SystemUtil.Run statement, refer to the Standard Windows section of the QuickTest Professional Object Model Reference.
The InvokeApplication statement is supported primarily for backward compatibility.
Syntax
InvokeApplication(Command [,StartIn])
Argument
Type
Description
Command
String
The path and command line options of the application to invoke.
StartIn
String
Optional. The working folder to which the Command path refers
Return Value
Boolean. If the function fails to open the application, False is returned.
Example
The following example uses the InvokeApplication function to open Internet Explorer.
InvokeApplication "E:\Program Files\Plus!\Microsoft Internet\IEXPLORE.EXE"

Is Operator

Compares two object reference variables.
result = object1 Is object2

Arguments

result
Any numeric variable.
object1
Any object name.
object2
Any object name.

Remarks

If object1 and object2 both refer to the same object, result is True; if they do not, result is False. Two variables can be made to refer to the same object in several ways.
In the following example, A has been set to refer to the same object as B:
Set A = B
The following example makes A and B refer to the same object as C:
Set A = C
Set B = C

IsArray Function

Returns a Boolean value indicating whether a variable is an array.
IsArray(varname)
The varname argument can be any variable.

Remarks

IsArray returns True if the variable is an array; otherwise, it returns False. IsArray is especially useful with variants containing arrays.
The following example uses the IsArray function to test whether MyVariable is an array:
Dim MyVariable
Dim MyArray(3)
MyArray(0) = "Sunday"
MyArray(1) = "Monday"
MyArray(2) = "Tuesday"
MyVariable = IsArray(MyArray) ' MyVariable contains "True".

IsDate Function

Returns a Boolean value indicating whether an expression can be converted to a date.
IsDate(expression)
The expression argument can be any date expression or string expression recognizable as a date or time.

Remarks

IsDate returns True if the expression is a date or can be converted to a valid date; otherwise, it returns False. In Microsoft Windows, the range of valid dates is January 1, 100 A.D. through December 31, 9999 A.D.; the ranges vary among operating systems.
The following example uses the IsDate function to determine whether an expression can be converted to a date:
Dim MyDate, YourDate, NoDate, MyCheck
MyDate = "October 19, 1962": YourDate = #10/19/62#: NoDate = "Hello"
MyCheck = IsDate(MyDate)   ' Returns True.
MyCheck = IsDate(YourDate)   ' Returns True.
MyCheck = IsDate(NoDate)   ' Returns False.

IsEmpty Function

Returns a Boolean value indicating whether a variable has been initialized.
IsEmpty(expression)
The expression argument can be any expression. However, because IsEmpty is used to determine if individual variables are initialized, the expression argument is most often a single variable name.

Remarks

IsEmpty returns True if the variable is uninitialized, or is explicitly set to Empty; otherwise, it returns False. False is always returned if expression contains more than one variable.
The following example uses the IsEmpty function to determine whether a variable has been initialized:
Dim MyVar, MyCheck
MyCheck = IsEmpty(MyVar)   ' Returns True.
MyVar = Null   ' Assign Null.
MyCheck = IsEmpty(MyVar)   ' Returns False.
MyVar = Empty   ' Assign Empty.
MyCheck = IsEmpty(MyVar)   ' Returns True.

IsNull Function

See Also

Returns a Boolean value that indicates whether an expression contains no valid data (Null).
IsNull(expression)
The expression argument can be any expression.

Remarks

IsNull returns True if expression is Null, that is, it contains no valid data; otherwise, IsNull returns False. If expression consists of more than one variable, Null in any constituent variable causes True to be returned for the entire expression.
The Null value indicates that the variable contains no valid data. Null is not the same as Empty, which indicates that a variable has not yet been initialized. It is also not the same as a zero-length string (""), which is sometimes referred to as a null string.
Caution   Use the IsNull function to determine whether an expression contains a Null value. Expressions that you might expect to evaluate to True under some circumstances, such as If Var = Null and If Var <> Null, are always False. This is because any expression containing a Null is itself Null, and therefore, False.
The following example uses the IsNull function to determine whether a variable contains a Null:
Dim MyVar, MyCheck
MyCheck = IsNull(MyVar)   ' Returns False.
MyVar = Null   ' Assign Null.
MyCheck = IsNull(MyVar)   ' Returns True.
MyVar = Empty   ' Assign Empty.
MyCheck = IsNull(MyVar)   ' Returns False.

IsNumeric Function

Returns a Boolean value indicating whether an expression can be evaluated as a number.
IsNumeric(expression)
The expression argument can be any expression.

Remarks

IsNumeric returns True if the entire expression is recognized as a number; otherwise, it returns False. IsNumeric returns False if expression is a date expression.
The following example uses the IsNumeric function to determine whether a variable can be evaluated as a number:
Dim MyVar, MyCheck
MyVar = 53   ' Assign a value.
MyCheck = IsNumeric(MyVar)   ' Returns True.
MyVar = "459.95"   ' Assign a value.
MyCheck = IsNumeric(MyVar)   ' Returns True.
MyVar = "45 Help"   ' Assign a value.
MyCheck = IsNumeric(MyVar)   ' Returns False

IsObject Function

Returns a Boolean value indicating whether an expression references a valid Automation object.
IsObject(expression)
The expression argument can be any expression.

Remarks

IsObject returns True if expression is a variable of Object subtype or a user-defined object; otherwise, it returns False.
The following example uses the IsObject function to determine if an identifier represents an object variable:
Dim MyInt, MyCheck, MyObject
Set MyObject = Me
MyCheck = IsObject(MyObject)   ' Returns True.
MyCheck = IsObject(MyInt)   ' Returns False.

Join Function

Returns a string created by joining a number of substrings contained in an array.
Join(list[, delimiter])

Arguments

list
Required. One-dimensional array containing substrings to be joined.
delimiter
Optional. String character used to separate the substrings in the returned string. If omitted, the space character (" ") is used. If delimiter is a zero-length string, all items in the list are concatenated with no delimiters.

Remarks

The following example uses the Join function to join the substrings of MyArray:
Dim MyString
Dim MyArray(3)
MyArray(0) = "Mr."
MyArray(1) = "John "
MyArray(2) = "Doe "
MyArray(3) = "III"
MyString = Join(MyArray) ' MyString contains "Mr. John Doe III".
 

LBound Function

Returns the smallest available subscript for the indicated dimension of an array.
LBound(arrayname[, dimension])

Arguments

arrayname
Name of the array variable; follows standard variable naming conventions.
dimension
Whole number indicating which dimension's lower bound is returned. Use 1 for the first dimension, 2 for the second, and so on. If dimension is omitted, 1 is assumed.

Remarks

The LBound function is used with the UBound function to determine the size of an array. Use the UBound function to find the upper limit of an array dimension.
The lower bound for any dimension is always 0.

LCase Function

Returns a string that has been converted to lowercase.
LCase(string)
The string argument is any valid string expression. If string contains Null, Null is returned.

Remarks

Only uppercase letters are converted to lowercase; all lowercase letters and non-letter characters remain unchanged.

The following example uses the LCase function to convert uppercase letters to lowercase:
Dim MyString
Dim LCaseString
MyString = "VBSCript"
LCaseString = LCase(MyString)   ' LCaseString contains "vbscript".
 

Left Function

Returns a specified number of characters from the left side of a string.
Left(string, length)

Arguments

string
String expression from which the leftmost characters are returned. If string contains Null, Null is returned.
length
Numeric expression indicating how many characters to return. If 0, a zero-length string("") is returned. If greater than or equal to the number of characters in string, the entire string is returned.

Remarks

To determine the number of characters in string, use the Len function.
The following example uses the Left function to return the first three characters of MyString:
Dim MyString, LeftString
MyString = "VBSCript"
LeftString = Left(MyString, 3) ' LeftString contains "VBS".
Note   The LeftB function is used with byte data contained in a string. Instead of specifying the number of characters to return, length specifies the number of bytes.
 

Len Function

Returns the number of characters in a string or the number of bytes required to store a variable.
Len(string | varname)

Arguments

string
Any valid string expression. If string contains Null, Null is returned.
varname
Any valid variable name. If varname contains Null, Null is returned.

Remarks

The following example uses the Len function to return the number of characters in a string:
Dim MyString
MyString = Len("VBSCRIPT") ' MyString contains 8.
Note   The LenB function is used with byte data contained in a string. Instead of returning the number of characters in a string, LenB returns the number of bytes used to represent that string.
 

LoadPicture Function

Returns a picture object. Available only on 32-bit platforms.
LoadPicture(picturename)
The picturename argument is a string expression that indicates the name of the picture file to be loaded.

Remarks

Graphics formats recognized by LoadPicture include bitmap (.bmp) files, icon (.ico) files, run-length encoded (.rle) files, metafile (.wmf) files, enhanced metafiles (.emf), GIF (.gif) files, and JPEG (.jpg) files.

Log Function

Returns the natural logarithm of a number.
Log(number)
The number argument can be any valid numeric expression greater than 0.

Remarks

The natural logarithm is the logarithm to the base e. The constant e is approximately 2.718282.
You can calculate base-n logarithms for any number x by dividing the natural logarithm of x by the natural logarithm of n as follows:
Logn(x) = Log(x) / Log(n)
The following example illustrates a custom Function that calculates base-10 logarithms:
Function Log10(X)
   Log10 = Log(X) / Log(10)
End Function

Mid Function

Returns a specified number of characters from a string.
Mid(string, start[, length])

Arguments

string
String expression from which characters are returned. If string contains Null, Null is returned.
start
Character position in string at which the part to be taken begins. If start is greater than the number of characters in string, Mid returns a zero-length string ("").
length
Number of characters to return. If omitted or if there are fewer than length characters in the text (including the character at start), all characters from the start position to the end of the string are returned.

Remarks

To determine the number of characters in string, use the Len function.
The following example uses the Mid function to return six characters, beginning with the fourth character, in a string:
Dim MyVar
MyVar = Mid("VB Script is fun!", 4, 6) ' MyVar contains "Script".
Note   The MidB function is used with byte data contained in a string. Instead of specifying the number of characters, the arguments specify numbers of bytes.

Minute

Returns a whole number between 0 and 59, inclusive, representing the minute of the hour.
Minute(time)
The time argument is any expression that can represent a time. If time contains Null, Null is returned.

Remarks

The following example uses the Minute function to return the minute of the hour:
Dim MyVar
MyVar = Minute(Now) 
 

Month Function

Returns a whole number between 1 and 12, inclusive, representing the month of the year.
Month(date)
The date argument is any expression that can represent a date. If date contains Null, Null is returned.

Remarks

The following example uses the Month function to return the current month:
Dim MyVar
MyVar = Month(Now) ' MyVar contains the number corresponding to
                   ' the current month.

MonthName Function

Returns a string indicating the specified month.
MonthName(month[, abbreviate])

Arguments

month
Required. The numeric designation of the month. For example, January is 1, February is 2, and so on.
abbreviate
Optional. Boolean value that indicates if the month name is to be abbreviated. If omitted, the default is False, which means that the month name is not abbreviated.

Remarks

The following example uses the MonthName function to return an abbreviated month name for a date expression:
Dim MyVar
MyVar = MonthName(10, True) ' MyVar contains "Oct". 
 

MsgBox Function

Displays a message in a dialog box, waits for the user to click a button, and returns a value indicating which button the user clicked.
MsgBox(prompt[, buttons][, title][, helpfile, context])

Arguments

prompt
String expression displayed as the message in the dialog box. The maximum length of prompt is approximately 1024 characters, depending on the width of the characters used. If prompt consists of more than one line, you can separate the lines using a carriage return character (Chr(13)), a linefeed character (Chr(10)), or carriage return–linefeed character combination (Chr(13) & Chr(10)) between each line.
buttons
Numeric expression that is the sum of values specifying the number and type of buttons to display, the icon style to use, the identity of the default button, and the modality of the message box. See Settings section for values. If omitted, the default value for buttons is 0.
title
String expression displayed in the title bar of the dialog box. If you omit title, the application name is placed in the title bar.
helpfile
String expression that identifies the Help file to use to provide context-sensitive Help for the dialog box. If helpfile is provided, context must also be provided. Not available on 16-bit platforms.
context
Numeric expression that identifies the Help context number assigned by the Help author to the appropriate Help topic. If context is provided, helpfile must also be provided. Not available on 16-bit platforms.

Settings

The buttons argument settings are:
Constant
Value
Description
vbOKOnly
   0
Display OK button only.
vbOKCancel
   1
Display OK and Cancel buttons.
vbAbortRetryIgnore
   2
Display Abort, Retry, and Ignore buttons.
vbYesNoCancel
   3
Display Yes, No, and Cancel buttons.
vbYesNo
   4
Display Yes and No buttons.
vbRetryCancel
   5
Display Retry and Cancel buttons.
vbCritical
16
Display Critical Message icon.
vbQuestion
32
Display Warning Query icon.
vbExclamation
48
Display Warning Message icon.
vbInformation
64
Display Information Message icon.
vbDefaultButton1
   0
First button is default.
vbDefaultButton2
 256
Second button is default.
vbDefaultButton3
 512
Third button is default.
vbDefaultButton4
 768
Fourth button is default.
vbApplicationModal
   0
Application modal; the user must respond to the message box before continuing work in the current application.
vbSystemModal
4096
System modal; all applications are suspended until the user responds to the message box.
The first group of values (0–5) describes the number and type of buttons displayed in the dialog box; the second group (16, 32, 48, 64) describes the icon style; the third group (0, 256, 512, 768) determines which button is the default; and the fourth group (0, 4096) determines the modality of the message box. When adding numbers to create a final value for the argument buttons, use only one number from each group.

Return Values

The MsgBox function has the following return values:
Constant
Value
Button
vbOK
1
OK
vbCancel
2
Cancel
vbAbort
3
Abort
vbRetry
4
Retry
vbIgnore
5
Ignore
vbYes
6
Yes
vbNo
7
No

Remarks

When both helpfile and context are provided, the user can press F1 to view the Help topic corresponding to the context.
If the dialog box displays a Cancel button, pressing the ESC key has the same effect as clicking Cancel. If the dialog box contains a Help button, context-sensitive Help is provided for the dialog box. However, no value is returned until one of the other buttons is clicked.
When the MsgBox function is used with Microsoft Internet Explorer, the title of any dialog presented always contains "VBScript:" to differentiate it from standard system dialogs.
The following example uses the MsgBox function to display a message box and return a value describing which button was clicked:
Dim MyVar
MyVar = MsgBox ("Hello World!", 65, "MsgBox Example")
   ' MyVar contains either 1 or 2, depending on which button is clicked.

Requirements

 

Now

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

Remarks

The following example uses the Now function to return the current date and time:
Dim MyVar
MyVar = Now ' MyVar contains the current date and time. 

Replace Function

Returns a string in which a specified substring has been replaced with another substring a specified number of times.
Replace(expression, find, replacewith[, start[, count[, compare]]])

Arguments

expression
Required. String expression containing substring to replace.
find
Required. Substring being searched for.
replacewith
Required. Replacement substring.
start
Optional. Position within expression where substring search is to begin. If omitted, 1 is assumed. Must be used in conjunction with count.
count
Optional. Number of substring substitutions to perform. If omitted, the default value is -1, which means make all possible substitutions. Must be used in conjunction with start.
compare
Optional. Numeric value indicating the kind of comparison to use when evaluating substrings. See Settings section for values. If omitted, the default value is 0, which means perform a binary comparison.

Settings

The compare argument can have the following values:
Constant
Value
Description
vbBinaryCompare
0
Perform a binary comparison.
vbTextCompare
1
Perform a textual comparison.

Return Values

Replace returns the following values:
If
Replace returns
expression is zero-length
Zero-length string ("").
expression is Null
An error.
find is zero-length
Copy of expression.
replacewith is zero-length
Copy of expression with all occurences of find removed.
start > Len(expression)
Zero-length string.
count is 0
Copy of expression.

Remarks

The return value of the Replace function is a string, with substitutions made, that begins at the position specified by start and and concludes at the end of the expression string. It is not a copy of the original string from start to finish.
The following example uses the Replace function to return a string:
Dim MyString
MyString = Replace("XXpXXPXXp", "p", "Y")   ' A binary comparison starting at the beginning of the string. Returns "XXYXXPXXY". 
MyString = Replace("XXpXXPXXp", "p", "Y",   ' A textual comparison starting at position 3. Returns "YXXYXXY". 3, -1, 1) 

Requirements

Replace Method

Replaces text found in a regular expression search.
object.Replace(string1, string2) 

Arguments

object
Required. Always the name of a RegExp object.
string1
Required. String1 is the text string in which the text replacement is to occur.
string2
Required. String2 is the replacement text string.

Remarks

The actual pattern for the text being replaced is set using the Pattern property of the RegExp object.
The Replace method returns a copy of string1 with the text of RegExp.Pattern replaced with string2. If no match is found, a copy of string1 is returned unchanged.
The following code illustrates use of the Replace method.
Function ReplaceTest(patrn, replStr)
  Dim regEx, str1               ' Create variables.
  str1 = "The quick brown fox jumped over the lazy dog."
  Set regEx = New RegExp            ' Create regular expression.
  regEx.Pattern = patrn            ' Set pattern.
  regEx.IgnoreCase = True            ' Make case insensitive.
  ReplaceTest = regEx.Replace(str1, replStr)   ' Make replacement.
End Function
 
MsgBox(ReplaceTest("fox", "cat"))      ' Replace 'fox' with 'cat'.
In addition, the Replace method can replace subexpressions in the pattern. The following call to the function shown in the previous example swaps each pair of words in the original string:
MsgBox(ReplaceText("(\S+)(\s+)(\S+)", "$3$2$1"))   ' Swap pairs of words.

RGB Function

Returns a whole number representing an RGB color value.
RGB(red, green, blue)

Arguments

red
Required. Number in the range 0-255 representing the red component of the color.
green
Required. Number in the range 0-255 representing the green component of the color.
blue
Required. Number in the range 0-255 representing the blue component of the color.

Remarks

Application methods and properties that accept a color specification expect that specification to be a number representing an RGB color value. An RGB color value specifies the relative intensity of red, green, and blue to cause a specific color to be displayed.
The low-order byte contains the value for red, the middle byte contains the value for green, and the high-order byte contains the value for blue.
For applications that require the byte order to be reversed, the following function will provide the same information with the bytes reversed:
Function RevRGB(red, green, blue)
   RevRGB= CLng(blue + (green * 256) + (red * 65536))
End Function
The value for any argument to RGB that exceeds 255 is assumed to be 255.

Right Function

Returns a specified number of characters from the right side of a string.
Right(string, length)

Arguments

string
String expression from which the rightmost characters are returned. If string contains Null, Null is returned.
length
Numeric expression indicating how many characters to return. If 0, a zero-length string is returned. If greater than or equal to the number of characters in string, the entire string is returned.

Remarks

To determine the number of characters in string, use the Len function.
The following example uses the Right function to return a specified number of characters from the right side of a string:
Dim AnyString, MyStr
AnyString = "Hello World"      ' Define string.
MyStr = Right(AnyString, 1)    ' Returns "d".
MyStr = Right(AnyString, 6)    ' Returns " World".
MyStr = Right(AnyString, 20)   ' Returns "Hello World".
Note   The RightB function is used with byte data contained in a string. Instead of specifying the number of characters to return, length specifies the number of bytes.
 

Rnd Function

Returns a random number.
Rnd[(number)]
The number argument can be any valid numeric expression.

Remarks

The Rnd function returns a value less than 1 but greater than or equal to 0. The value of number determines how Rnd generates a random number:
If number is
Rnd generates
Less than zero
The same number every time, using number as the seed.
Greater than zero
The next random number in the sequence.
Equal to zero
The most recently generated number.
Not supplied
The next random number in the sequence.
For any given initial seed, the same number sequence is generated because each successive call to the Rnd function uses the previous number as a seed for the next number in the sequence.
Before calling Rnd, use the Randomize statement without an argument to initialize the random-number generator with a seed based on the system timer.
To produce random integers in a given range, use this formula:
Int((upperbound - lowerbound + 1) * Rnd + lowerbound)
Here, upperbound is the highest number in the range, and lowerbound is the lowest number in the range.
Note   To repeat sequences of random numbers, call Rnd with a negative argument immediately before using Randomize with a numeric argument. Using Randomize with the same value for number does not repeat the previous sequence.

Round Function

Returns a number rounded to a specified number of decimal places.
Round(expression[, numdecimalplaces])

Arguments

expression
Required. Numeric expression being rounded.
numdecimalplaces
Optional. Number indicating how many places to the right of the decimal are included in the rounding. If omitted, integers are returned by the Round function.

Remarks

The following example uses the Round function to round a number to two decimal places:
Dim MyVar, pi
pi = 3.14159
MyVar = Round(pi, 2) ' MyVar contains 3.14.

ScriptEngine Function

Returns a string representing the scripting language in use.
ScriptEngine

Return Values

The ScriptEngine function can return any of the following strings:
String
Description
VBScript
Indicates that Microsoft® Visual Basic® Scripting Edition is the current scripting engine.
JScript
Indicates that Microsoft JScript® is the current scripting engine.
VBA
Indicates that Microsoft Visual Basic for Applications is the current scripting engine.

Remarks

The following example uses the ScriptEngine function to return a string describing the scripting language in use:
Function GetScriptEngineInfo
   Dim s
   s = ""   ' Build string with necessary info.
   s = ScriptEngine & " Version "
   s = s & ScriptEngineMajorVersion & "."
   s = s & ScriptEngineMinorVersion & "."
   s = s & ScriptEngineBuildVersion 
   GetScriptEngineInfo = s   ' Return the results.
End Function
 

ScriptEngineBuildVersion Function

Returns the build version number of the scripting engine in use.
ScriptEngineBuildVersion

Remarks

The return value corresponds directly to the version information contained in the DLL for the scripting language in use.
The following example uses the ScriptEngineBuildVersion function to return the build version number of the scripting engine:
Function GetScriptEngineInfo
   Dim s
   s = ""   ' Build string with necessary info.
   s = ScriptEngine & " Version "
   s = s & ScriptEngineMajorVersion & "."
   s = s & ScriptEngineMinorVersion & "."
   s = s & ScriptEngineBuildVersion
   GetScriptEngineInfo = s   ' Return the results.
End Function
 

ScriptEngineMajorVersion Function

Returns the major version number of the scripting engine in use.
ScriptEngineMajorVersion

Remarks

The return value corresponds directly to the version information contained in the DLL for the scripting language in use.
The following example uses the ScriptEngineMajorVersion function to return the version number of the scripting engine:
Function GetScriptEngineInfo
   Dim s
   s = ""   ' Build string with necessary info.
   s = ScriptEngine & " Version "
   s = s & ScriptEngineMajorVersion & "."
   s = s & ScriptEngineMinorVersion & "."
   s = s & ScriptEngineBuildVersion 
   GetScriptEngineInfo = s   ' Return the results.
End Function
 

ScriptEngineMinorVersion Function

Returns the minor version number of the scripting engine in use.
ScriptEngineMinorVersion

Remarks

The return value corresponds directly to the version information contained in the DLL for the scripting language in use.
The following example uses the ScriptEngineMinorVersion function to return the minor version number of the scripting engine:
Function GetScriptEngineInfo
   Dim s
   s = ""   ' Build string with necessary info.
   s = ScriptEngine & " Version "
   s = s & ScriptEngineMajorVersion & "."
   s = s & ScriptEngineMinorVersion & "."
   s = s & ScriptEngineBuildVersion 
   GetScriptEngineInfo = s   ' Return the results.
End Function
 

Second Function

Returns a whole number between 0 and 59, inclusive, representing the second of the minute.
Second(time)
The time argument is any expression that can represent a time. If time contains Null, Null is returned.

Remarks

The following example uses the Second function to return the current second:
Dim MySec
MySec = Second(Now)
   ' MySec contains the number representing the current second.
 

SetLastError Statement

Description
Inserts a VBScript error into the test or component script.
Syntax
SetLastError(Error)
Argument
Type
Description
Error
Integer
The error.
Example
The following example uses the SetLastError function to place the "Out of memory" error into the test script. For a list of VBScript errors, refer to the Microsoft VBScript Reference (Help > QuickTest Professional Help > Microsoft Windows Script Technologies).
Browser("Mercury Tours").Page("Mercury Tours").Image("Login").Click 11, -18
SetLastError(7)
Browser("Mercury Tours").Page("Welcome to Mercury").Image("Search Flights").Click

Sgn Function

Returns an integer indicating the sign of a number.
Sgn(number)
The number argument can be any valid numeric expression.

Return Values

The Sgn function has the following return values:
If number is
Sgn returns
Greater than zero
1
Equal to zero
0
Less than zero
-1

Remarks

The sign of the number argument determines the return value of the Sgn function.
The following example uses the Sgn function to determine the sign of a number:
Dim MyVar1, MyVar2, MyVar3, MySign
MyVar1 = 12: MyVar2 = -2.4: MyVar3 = 0
MySign = Sgn(MyVar1)   ' Returns 1.
MySign = Sgn(MyVar2)   ' Returns -1.
MySign = Sgn(MyVar3)   ' Returns 0.

Requirements

 

Sin Function

Returns the sine of an angle.
Sin(number)
The number argument can be any valid numeric expression that expresses an angle in radians.

Remarks

The Sin function takes an angle and returns the ratio of two sides of a right triangle. The ratio is the length of the side opposite the angle divided by the length of the hypotenuse. The result lies in the range -1 to 1.
To convert degrees to radians, multiply degrees by pi /180. To convert radians to degrees, multiply radians by 180/pi.
The following example uses the Sin function to return the sine of an angle:
Dim MyAngle, MyCosecant
MyAngle = 1.3   ' Define angle in radians.
MyCosecant = 1 / Sin(MyAngle)   ' Calculate cosecant.
 

Space Function

Returns a string consisting of the specified number of spaces.
Space(number)
The number argument is the number of spaces you want in the string.

Remarks

The following example uses the Space function to return a string consisting of a specified number of spaces:
Dim MyString
MyString = Space(10)   ' Returns a string with 10 spaces.
MyString = "Hello" & Space(10) & "World" ' Insert 10 spaces between two strings.

Requirements

Split Function

Returns a zero-based, one-dimensional array containing a specified number of substrings.
Split(expression[, delimiter[, count[, compare]]])

Arguments

expression
Required. String expression containing substrings and delimiters. If expression is a zero-length string, Split returns an empty array, that is, an array with no elements and no data.
delimiter
Optional. String character used to identify substring limits. If omitted, the space character (" ") is assumed to be the delimiter. If delimiter is a zero-length string, a single-element array containing the entire expression string is returned.
count
Optional. Number of substrings to be returned; -1 indicates that all substrings are returned.
compare
Optional. Numeric value indicating the kind of comparison to use when evaluating substrings. See Settings section for values.

Settings

The compare argument can have the following values:
Constant
Value
Description
vbBinaryCompare
0
Perform a binary comparison.
vbTextCompare
1
Perform a textual comparison.

Remarks

The following example uses the Split function to return an array from a string. The function performs a textual comparison of the delimiter, and returns all of the substrings.
Dim MyString, MyArray, Msg
MyString = "VBScriptXisXfun!"
MyArray = Split(MyString, "x", -1, 1)
' MyArray(0) contains "VBScript".
' MyArray(1) contains "is".
' MyArray(2) contains "fun!".
Msg = MyArray(0) & " " & MyArray(1)
Msg = Msg   & " " & MyArray(2)
MsgBox Msg
 
 

Sqr Function

Returns the square root of a number.
Sqr(number)
The number argument can be any valid numeric expression greater than or equal to 0.

Remarks

The following example uses the Sqr function to calculate the square root of a number:
Dim MySqr
MySqr = Sqr(4)   ' Returns 2.
MySqr = Sqr(23)   ' Returns 4.79583152331272.
MySqr = Sqr(0)   ' Returns 0.
MySqr = Sqr(-4)   ' Generates a run-time error.
 

StrComp Function

Returns a value indicating the result of a string comparison.
StrComp(string1, string2[, compare])

Arguments

string1
Required. Any valid string expression.
string2
Required. Any valid string expression.
compare
Optional. Numeric value indicating the kind of comparison to use when evaluating strings. If omitted, a binary comparison is performed. See Settings section for values.

Settings

The compare argument can have the following values:
Constant
Value
Description
vbBinaryCompare
0
Perform a binary comparison.
vbTextCompare
1
Perform a textual comparison.

Return Values

The StrComp function has the following return values:
If
StrComp returns
string1 is less than string2
-1
string1 is equal to string2
0
string1 is greater than string2
1
string1 or string2 is Null
Null

Remarks

The following example uses the StrComp function to return the results of a string comparison. If the third argument is 1, a textual comparison is performed; if the third argument is 0 or omitted, a binary comparison is performed.
Dim MyStr1, MyStr2, MyComp
MyStr1 = "ABCD": MyStr2 = "abcd"   ' Define variables.
MyComp = StrComp(MyStr1, MyStr2, 1)   ' Returns 0.
MyComp = StrComp(MyStr1, MyStr2, 0)   ' Returns -1.
MyComp = StrComp(MyStr2, MyStr1)   ' Returns 1.
 

String Function

Returns a repeating character string of the length specified.
String(number, character)

Arguments

number
Length of the returned string. If number contains Null, Null is returned.
character
Character code specifying the character or string expression whose first character is used to build the return string. If character contains Null, Null is returned.

Remarks

If you specify a number for character greater than 255, String converts the number to a valid character code using the formula:
character Mod 256
The following example uses the String function to return repeating character strings of the length specified:
Dim MyString
MyString = String(5, "*")   ' Returns "*****".
MyString = String(5, 42)   ' Returns "*****".
MyString = String(10, "ABC")   ' Returns "AAAAAAAAAA".

Requirements

StrReverse Function

Returns a string in which the character order of a specified string is reversed.
StrReverse(string1)
The string1 argument is the string whose characters are to be reversed. If string1 is a zero-length string (""), a zero-length string is returned. If string1 is Null, an error occurs.

Remarks

The following example uses the StrReverse function to return a string in reverse order:
Dim MyStr
MyStr = StrReverse("VBScript") ' MyStr contains "tpircSBV".

Tan Function

Returns the tangent of an angle.
Tan(number)
The number argument can be any valid numeric expression that expresses an angle in radians.

Remarks

Tan takes an angle and returns the ratio of two sides of a right triangle. The ratio is the length of the side opposite the angle divided by the length of the side adjacent to the angle.
To convert degrees to radians, multiply degrees by pi /180. To convert radians to degrees, multiply radians by 180/pi.
The following example uses the Tan function to return the tangent of an angle:
Dim MyAngle, MyCotangent
MyAngle = 1.3   ' Define angle in radians.
MyCotangent = 1 / Tan(MyAngle)   ' Calculate cotangent
 

Time Function

Returns a Variant of subtype Date indicating the current system time.
Time

Remarks

The following example uses the Time function to return the current system time:
Dim MyTime
MyTime = Time   ' Return current system time.
 

Timer Function

Returns the number of seconds that have elapsed since 12:00 AM (midnight).
Timer

Remarks

The following example uses the Timer function to determine the time it takes to iterate a For...Next loop N times:
Function TimeIt(N)
   Dim StartTime, EndTime
   StartTime = Timer
   For I = 1 To N
   Next
   EndTime = Timer
   TimeIt = EndTime - StartTime
End Function 
 

TimeSerial Function

Returns a Variant of subtype Date containing the time for a specific hour, minute, and second.
TimeSerial(hour, minute, second)

Arguments

hour
Number between 0 (12:00 A.M.) and 23 (11:00 P.M.), inclusive, or a numeric expression.
minute
Any numeric expression.
second
Any numeric expression.

Remarks

To specify a time, such as 11:59:59, the range of numbers for each TimeSerial argument should be in the accepted range for the unit; that is, 0–23 for hours and 0–59 for minutes and seconds. However, you can also specify relative times for each argument using any numeric expression that represents some number of hours, minutes, or seconds before or after a certain time.
The following example uses expressions instead of absolute time numbers. The TimeSerial function returns a time for 15 minutes before (-15) six hours before noon (12 - 6), or 5:45:00 A.M.
Dim MyTime1
MyTime1 = TimeSerial(12 - 6, -15, 0) ' Returns 5:45:00 AM.
When any argument exceeds the accepted range for that argument, it increments to the next larger unit as appropriate. For example, if you specify 75 minutes, it is evaluated as one hour and 15 minutes. However, if any single argument is outside the range -32,768 to 32,767, or if the time specified by the three arguments, either directly or by expression, causes the date to fall outside the acceptable range of dates, an error occurs.

TimeValue

Returns a Variant of subtype Date containing the time.
TimeValue(time)
The time argument is usually a string expression representing a time from 0:00:00 (12:00:00 A.M.) to 23:59:59 (11:59:59 P.M.), inclusive. However, time can also be any expression that represents a time in that range. If time contains Null, Null is returned.

Remarks

You can enter valid times using a 12-hour or 24-hour clock. For example, "2:24PM" and "14:24" are both valid time arguments. If the time argument contains date information, TimeValue doesn't return the date information. However, if time includes invalid date information, an error occurs.
The following example uses the TimeValue function to convert a string to a time. You can also use date literals to directly assign a time to a Variant (for example, MyTime = #4:35:17 PM#).
Dim MyTime
MyTime = TimeValue("4:35:17 PM")   ' MyTime contains 4:35:17 PM.

RequirementsTypeName Function

Returns a string that provides Variant subtype information about a variable.
TypeName(varname)
The required varname argument can be any variable.

Return Values

The TypeName function has the following return values:
Value
Description
Byte
Byte value
Integer
Integer value
Long
Long integer value
Single
Single-precision floating-point value
Double
Double-precision floating-point value
Currency
Currency value
Decimal
Decimal value
Date
Date or time value
String
Character string value
Boolean
Boolean value; True or False
Empty
Unitialized
Null
No valid data

Actual type name of an object
Object
Generic object
Unknown
Unknown object type
Nothing
Object variable that doesn't yet refer to an object instance
Error
Error

UBound Function

Returns the largest available subscript for the indicated dimension of an array.
UBound(arrayname[, dimension])

Arguments

arrayname
Required. Name of the array variable; follows standard variable naming conventions.
dimension
Optional. Whole number indicating which dimension's upper bound is returned. Use 1 for the first dimension, 2 for the second, and so on. If dimension is omitted, 1 is assumed.

Remarks

The UBound function is used with the LBound function to determine the size of an array. Use the LBound function to find the lower limit of an array dimension.
The lower bound for any dimension is always 0. As a result, UBound returns the following values for an array with these dimensions:
Dim A(100,3,4)
Statement
Return Value
UBound(A, 1)
100
UBound(A, 2)
3
UBound(A, 3)
4

UCase Function

Returns a string that has been converted to uppercase.
UCase(string)
The string argument is any valid string expression. If string contains Null, Null is returned.

Remarks

Only lowercase letters are converted to uppercase; all uppercase letters and non-letter characters remain unchanged.
The following example uses the UCase function to return an uppercase version of a string:
Dim MyWord
MyWord = UCase("Hello World")   ' Returns "HELLO WORLD".

VarType Function

Returns a value indicating the subtype of a variable.
VarType(varname)
The varname argument can be any variable.

Return Values

The VarType function returns the following values:
Constant
Value
Description
vbEmpty
0
Empty (uninitialized)
vbNull
1
Null (no valid data)
vbInteger
2
Integer
vbLong
3
Long integer
vbSingle
4
Single-precision floating-point number
vbDouble
5
Double-precision floating-point number
vbCurrency
6
Currency
vbDate
7
Date
vbString
8
String
vbObject
9
Automation object
vbError
10
Error
vbBoolean
11
Boolean
vbVariant
12
Variant (used only with arrays of Variants)
vbDataObject
13
A data-access object
vbByte
17
Byte
vbArray
8192
Array
Note   These constants are specified by VBScript. As a result, the names can be used anywhere in your code in place of the actual values.

Remarks

The VarType function never returns the value for Array by itself. It is always added to some other value to indicate an array of a particular type. The value for Variant is only returned when it has been added to the value for Array to indicate that the argument to the VarType function is an array. For example, the value returned for an array of integers is calculated as 2 + 8192, or 8194. If an object has a default property, VarType (object) returns the type of its default property.
The following example uses the VarType function to determine the subtype of a variable.
Dim MyCheck
MyCheck = VarType(300)          ' Returns 2.
MyCheck = VarType(#10/19/62#)   ' Returns 7.
MyCheck = VarType("VBScript")   ' Returns 8.

Weekday Function

Returns a whole number representing the day of the week.
Weekday(date, [firstdayofweek])

Arguments

date
Any expression that can represent a date. If date contains Null, Null is returned.
firstdayofweek
A constant that specifies the first day of the week. If omitted, vbSunday is assumed.

Settings

The firstdayofweek argument has these settings:
Constant
Value
Description
vbUseSystemDayOfWeek
0
Use National Language Support (NLS) API setting.
vbSunday
1
Sunday
vbMonday
2
Monday
vbTuesday
3
Tuesday
vbWednesday
4
Wednesday
vbThursday
5
Thursday
vbFriday
6
Friday
vbSaturday
7
Saturday

Return Values

The Weekday function can return any of these values:
Constant
Value
Description
vbSunday
1
Sunday
vbMonday
2
Monday
vbTuesday
3
Tuesday
vbWednesday
4
Wednesday
vbThursday
5
Thursday
vbFriday
6
Friday
vbSaturday
7
Saturday

Remarks

The following example uses the Weekday function to obtain the day of the week from a specified date:
Dim MyDate, MyWeekDay
MyDate = #October 19, 1962#   ' Assign a date.
MyWeekDay = Weekday(MyDate)   ' MyWeekDay contains 6 because MyDate represents a Friday.

Requirements

WeekdayName Function

Returns a string indicating the specified day of the week.
WeekdayName(weekday, abbreviate, firstdayofweek)

Arguments

weekday
Required. The numeric designation for the day of the week. Numeric value of each day depends on setting of the firstdayofweek setting.
abbreviate
Optional. Boolean value that indicates if the weekday name is to be abbreviated. If omitted, the default is False, which means that the weekday name is not abbreviated.
firstdayofweek
Optional. Numeric value indicating the first day of the week. See Settings section for values.

Settings

The firstdayofweek argument can have the following values:
Constant
Value
Description
vbUseSystemDayOfWeek
0
Use National Language Support (NLS) API setting.
vbSunday
1
Sunday (default)
vbMonday
2
Monday
vbTuesday
3
Tuesday
vbWednesday
4
Wednesday
vbThursday
5
Thursday
vbFriday
6
Friday
vbSaturday
7
Saturday

Year Function

Returns a whole number representing the year.
Year(date)
The date argument is any expression that can represent a date. If date contains Null, Null is returned.

Remarks

The following example uses the Year function to obtain the year from a specified date:
Dim MyDate, MyYear
MyDate = #October 19, 1962#   ' Assign a date.
MyYear = Year(MyDate)         ' MyYear contains 1962.

 










UTILITY FUNCTIONS

FireEvent Method (ActiveX)



Description
Simulates an event on the ActiveX object.
Remarks
The event is sent to the container of the ActiveX object and does not affect the ActiveX object itself. For example, simulating a click event does not actually perform the click.
Syntax
object.FireEvent EventName, [Args()]
Argument                      Description
object                             A test object of type ActiveX.
EventName                     Required. A Variant value. The name of the event to simulate. The list of possible events depends on the object.
Args()                             Optional. An array of Variant values. Zero or more arguments of the event. The list of arguments depends on the EventName.
Return Type
None  
Sub FireEvent_Example()
'The following example uses the FireEvent method to simulate a
'click event on the Save button.

Browser("Homepage").Page("Welcome").AcxButton("Save").FireEvent "Click"


End Sub


Encrypt Method

Description
Encrypts a string.
Syntax
Crypt.Encrypt(Data)
Argument
Type
Description
Data
String
The string to encrypt.
Return Value
String
Example
In the following example, a password is taken from a database and encrypted using the Encrypt method, and then placed in the password edit box using the SetSecure method.
pwd = "GetPasswordfromSomewhere"
e_pwd = Crypt.Encrypt(pwd)
Browser("dfgd").Dialog("pass").WinEdit("pwd").SetSecure e_pwd
DATA TABLE METHODS

AddSheet Method

Description
Adds the specified sheet to the run-time Data Table and returns the sheet so that you can directly set properties of the new sheet in the same statement.
Syntax
DataTable.AddSheet(SheetName)
Argument                      Type                Description
SheetName                     String               Assigns a name to the new sheet.
Return Value
Example
The following example uses the AddSheet method to create the new sheet, "MySheet" in the run-time Data Table and then adds a parameter to the new sheet.
Variable=DataTable.AddSheet ("MySheet").AddParameter("Time", "8:00")

DeleteSheet Method

Description
Deletes the specified sheet from the run-time Data Table.
Syntax
DataTable.DeleteSheet SheetID
Argument   Type      Description
SheetID     Variant  Identifies the sheet to be returned. The SheetID can be the sheet name or index. Index values begin with 1.
Example
The following example uses the DeleteSheet method to delete the sheet, "MySheet" from the run-time Data Table.
DataTable.DeleteSheet "MySheet"

Export Method

Description
Saves a copy of the run-time Data Table in the specified location.
Syntax
DataTable.Export(FileName)
Argument      Type      Description
FileName        String     The full path of the location to which the Data Table should be exported.
Example
The following example uses the Export method to save a copy of the test's Data Table in C:\flights.xls.
DataTable.Export ("C:\flights.xls")

ExportSheet Method

Description
Exports a specified sheet of the run-time Data Table to the specified file.
  • If the specified file does not exist, a new file is created and the specified sheet is saved.
  • If the current file exists, but the file does not contain a sheet with the specified sheet name, the sheet is inserted as the last sheet of the file.
  • If the current file exists and the file contains the specified sheet, the exported sheet overwrites the existing sheet.
Syntax
DataTable.ExportSheet(FileName, DTSheet)
Argument
Type
Description
FileName
String
The full path of the Excel table to which you want to export a sheet.
DTSheet
Variant
The name or index of the run-time Data Table sheet that you want to export. Index values begin with 1.
Example
The following example uses the ExportSheet method to save the first sheet of the run-time Data Table to the name.xls file.
DataTable.ExportSheet "C:\name.xls" ,1

GetCurrentRow Method

Description
Returns the current (active) row in the first sheet in the run-time Data Table (the global sheet for tests, or the business component sheet for Business Components).
Syntax
DataTable.GetCurrentRow
Return Value
Number
Example
The following example uses the GetCurrentRow method to retrieve the row currently being used in run-time Data Table and writes it to the report.
row = DataTable.GetCurrentRow
Reporter.ReportEvent 1, "Row Number", row

GetRowCount Method

Description
Returns the total number of rows in the longest column in the first sheet in the run-time Data Table (the global sheet for tests, or the business component sheet for Business Components).
Syntax
DataTable.GetRowCount
Return Value
Number
Example
The following example uses the GetRowCount method to find the total number of rows in the longest column of the MySheet run-time data sheet and writes it to the report.
rowcount = DataTable.GetSheet("MySheet").GetRowCount
Reporter.ReportEvent 2, "There are " &rowcount, "rows in the data sheet."

GetSheet Method

Description
Returns the specified sheet from the run-time Data Table.
Syntax
DataTable.GetSheet(SheetID)
Argument
Type
Description
SheetID
Variant
Identifies the sheet to be returned. The SheetID can be the sheet name or index. Index values begin with 1.
Return Value
Example
The following example uses the GetSheet method to return the "MySheet" sheet of the run-time Data Table in order to add a parameter to it.
MyParam=DataTable.GetSheet ("MySheet").AddParameter("Time", "8:00")
You can also use this to add a parameter to the "MySheet" local sheet (note that no value is returned).
DataTable.GetSheet ("MySheet").AddParameter "Time", "8:00"

GetSheetCount Method

Description
Returns the total number of sheets in the run-time Data Table.
Syntax
DataTable.GetSheetCount
Return Value
Number
Example
The following example uses the GetSheetCount method to find the total number of sheets in the run-time Data Table and writes it to the report.
sheetcount = DataTable.GetSheetCount
Reporter.ReportEvent 0, "Sheet number", "There are " & sheetcount & " sheets in the Data Table."

GlobalSheet Property

Description
Returns the first sheet in the run-time Data Table (the global sheet for tests, or the business component sheet for Business Components).
Syntax
DataTable.GlobalSheet
Example
The following example uses the GlobalSheet property to return the global sheet of the run-time Data Table in order to add a parameter (column) to it.
ParamValue=DataTable.GlobalSheet.AddParameter("Time", "5:45")
You can also use this method to add a parameter to the global sheet (note that no value is returned).
DataTable.GlobalSheet.AddParameter "Time", "5:45"

Import Method

Description
Imports the specified Microsoft Excel file to the run-time Data Table.
Notes:
The imported table must match the test or component. The column names must match the parameters in the test or component, and the sheet names (for tests) must match the action names.
If you import an Excel table containing combo box or list cells, conditional formatting, or other special cell formats, the formats are not imported and the cell is displayed in the Data Table with a fixed value.
Syntax
DataTable.Import(FileName)
Argument
Type
Description
FileName
String
The full path of the Excel table to import.
Example
The imported table replaces all data in the existing run-time Data Table (including all data sheets).
The following example uses the Import method to import the flights.xls table to the run-time Data Table.
DataTable.Import ("C:\flights.xls")

ImportSheet Method

Description
Imports a sheet of a specified file to a specified sheet in the run-time Data Table. The data in the imported sheet replaces the data in the destination sheet (see SheetDest argument).
Notes:
The column headings in the sheet you import must match the Data Table parameter names in the action for which the sheet is being imported. Otherwise, your test or component may fail.
The sheet you import automatically takes the name of the sheet it replaces.
If you import an excel sheet containing combo box or list cells, conditional formatting, or other special cell formats, the formats are not imported and the cell is displayed in the Data Table with a fixed value.
Syntax
DataTable.ImportSheet(FileName, SheetSource, SheetDest)
Argument
Type
Description
FileName
String
The full path of the Excel table from which you want to import a sheet.
SheetSource
Variant
The name or index of the sheet in the file that you want to import. Index values begin with 1.
SheetDest
Variant
The name or index of the sheet in the Data Table that you want to replace with the SheetSource. Index values begin with 1.
Example
The following example uses the ImportSheet method to import the first sheet of the name.xls table to the name sheet in the test's run-time Data Table.
DataTable.ImportSheet "C:\name.xls" ,1 ,"name"

LocalSheet Property

Description
Returns the current (active) local sheet of the run-time Data Table.
Syntax
DataTable.LocalSheet
Example
The following example uses the LocalSheet property to return the local sheet of the run-time Data Table in order to add a parameter (column) to it.
MyParam=DataTable.LocalSheet.AddParameter("Time", "5:45")

RawValue Property

Description
Retrieves the raw value of the cell in the specified parameter and the current row of the run-time Data Table. The raw value is the actual string written in a cell before the cell has been computed, such as the actual text from a formula.
Syntax
DataTable.RawValue ParameterID [, SheetID]
Argument
Type
Description
ParameterID
Variant
Identifies the parameter (column) of the value to be set/retrieved. Index values begin with 1.
Note: The specified value must be an actual column header name that has been defined as a Data Table parameter. Entering A (or another default column label) as the column name is not valid unless A has explicitly been set as the name of a Data Table parameter.
SheetID
Variant
Optional. Identifies the sheet to be returned. The SheetID can be the sheet name, index or dtLocalSheet, or dtGlobalSheet.
If no Sheet is specified, the first sheet in the run-time Data Table is used (the global sheet for tests, or the component sheet for business components). Index values begin with 1.
Example
The following example uses the RawValue property to find the formula used in the current row of the Date column in the ActionA sheet in the run-time Data Table. The statement below returns the value: =NOW()
FormulaVal=DataTable.RawValue ("Date", "ActionA")

SetCurrentRow Method

Description
Sets the specified row as the current (active) row in the run-time Data Table.
Note: You can only set a row that contains at least one value.
Syntax
DataTable.SetCurrentRow(RowNumber)
Argument
Type
Description
RowNumber
Number
Indicates the number of the row to set as the active row. The first row is numbered 1.
Example
The following example uses the SetCurrentRow method to change the active row to the second row in the global run-time Data Table.
DataTable.SetCurrentRow (2)

SetNextRow Method

Description
Sets the row after the current (active) row as the new current row in the run-time Data Table.
Note: You can only set a row that contains at least one value. If the current row is the last row in the Data Table, applying this method sets the first row in the Data Table as the new current row.
Syntax
DataTable.SetNextRow
Example
The following example uses the SetNextRow method to change the active row to the next row in the global run-time Data Table.
DataTable.SetNextRow

SetPrevRow Method

Description
Sets the row above the current (active) row as the new current (active) row in the run-time Data Table.
Note: If the current row is the first row in the Data Table, applying this method sets the last row in the Data Table as the new current row.
Syntax
DataTable.SetPrevRow
Example
The following example uses the SetPrevRow method to change the active row to the previous row in the global run-time Data Table.
DataTable.SetPrevRow

Value Property

Description
DataTable default property. Retrieves or sets the value of the cell in the specified parameter and the current row of the run-time Data Table.
Note: This property returns the computed value of the cell. For example, if the cell contains a formula, the method returns True or False.
Syntax
To find the value:
DataTable.Value(ParameterID [, SheetID])
or
DataTable(ParameterID [, SheetID])
To set the value:
DataTable.Value(ParameterID [, SheetID])=NewValue
or
DataTable(ParameterID [, SheetID]) =NewValue
CaptureBitmap Method (Desktop)
Description
Saves a screen capture of the object as a .png or .bmp image using the specified file name.
Remarks
This method is common to all standard Windows test objects.  For additional information and examples of usage, see CaptureBitmap.
Syntax
object.CaptureBitmap Filename, [OverrideExisting]
Argument
Description
object
A test object of type Desktop.
Filename
Required. A String value.
OverrideExisting
Optional. A Long value.
Return Type
None  
Description
Saves a screen capture of the object as a .png or .bmp image using the specified file name.
Syntax
object.CaptureBitmap FullFileName, [OverrideExisting]

Argument
Description

object
Any Standard Windows test object.

FullFileName
Required. A String value.

OverrideExisting
Optional. A Boolean value. Indicates whether the captured image should be overwritten if the image file already exists in the test results folder.
Possible values:
True
False
(default
Example 1: Capture an Image To a Unique Folder






Sub CaptureBitmap_Example1()
'The following example uses the CaptureBitmap method to capture a
'screen shot of the Internet Options dialog box. The file is
'automatically saved to a different folder (the test run results
'folder) in each run.

Browser("Mercury Tours").Dialog("Internet Options").CaptureBitmap "internet_options.bmp"

End Sub


Example 2: Capture an Image Using an Absolute Path


Sub CaptureBitmap_Example2()
'The following example uses the CaptureBitmap method to capture a
'screen shot of the Internet Options dialog box. The image is saved to an
'absolute path. Each time the CaptureBitmap statement runs,
'QuickTest overwrites the previous image with the new one.
Browser("Mercury Tours").Dialog("Internet Options").CaptureBitmap "C:\ScreenCaps\internet_options.bmp", True
'In the statement below, the image is saved to the absolute path,
'but if the statement runs more than once, then the existing file is
'saved, and later captures are not.
Browser("Mercury Tours").Dialog("Internet Options").CaptureBitmap "C:\ScreenCaps\internet_options.bmp", False
End Sub


ChildObjects Method (Common)
Description
Returns the collection of child objects contained within the object.
Syntax
object.ChildObjects (pDescription)
Argument
Description
object
Any Standard Windows test object.
pDescription
Required. An Object object. A Properties (collection) object. 
Tip: You can can retrieve a Properties collection using the GetTOProperties method or you can build a Properties collection object using the Description object.  For more information on the Description object, refer to the Utility section of the QuickTest Professional Object Model Reference.
Return Type
An Object object.  
Example: Determine How Many Objects in a Parent Item 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(descr, ",")
For i = 0 To UBound(arProps)
arProp = Split(arProps(i), ":=")
    If UBound(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 = "Object Unique"
ElseIf children.Count = 0 Then
CheckObjectDesription = "Object Not Found"
Else
CheckObjectDesription = "Object Not Unique"
End If
End Function


RunAnalog Method (Desktop)



Description
Runs the specified analog track.
Remarks
Analog recording mode records exact mouse and keyboard operations. The track of the operations recorded are stored in an external data file. For more information on analog recording, refer to the QuickTest Professional User’s Guide.
Syntax
object.RunAnalog ActionId, [Speed]
Argument
Description
object
A test object of type Desktop.
ActionId
Required. A String value.
The name of the track that is called by the method. The track contains all the analog steps recorded and is stored in an external data file. One external data file is created per action and the file contains all the tracks recorded for that action.

Note: You must use a valid and existing track as the method argument.
Speed
Optional. An Integer value. Specifies the test run speed for the analog track.

Possible values:
0—Default. Fast. Runs all recorded actions as quickly as possible.
1—Normal. Runs using the recorded speed.
Return Type
None  
Example 1: Run an Analog Track File in Fast Run Speed


Sub RunAnalog_Example1()
'The following example uses the RunAnalog method to perform the
'mouse drags used to replicate a user's signature on the screen using
'the Fast run speed. QuickTest clicks in the signature area of a
'flight reservation application and then uses the RunAnalog method
'to run the external Track1 analog file.


Window("Flight Reservation").Dialog("Fax Order No.").Click 216, 204
Desktop.RunAnalog "Track1"

End Sub


Example 2: Run an Analog Track File in Normal Run Speed


Sub RunAnalog_Example2()
'The following example uses the RunAnalog method to perform the mouse
'drags used to replicate a user's signature on the screen using the
'Normal run speed.

Window("Flight Reservation").Dialog("Fax Order No.").Click 216, 204
Desktop.RunAnalog "Track1", 1

End Sub


ExternalFileName Property

Description
Returns the name of the loaded external environment variable file specified in the Environment tab of the Test Settings or Business Component Settings dialog box. If no external environment variable file is loaded, returns an empty string.
Syntax
Environment.ExternalFileName
Example
The following example uses the ExternalFileName property to check whether an environment variable file is loaded, and if not, loads a specific file and then displays one of the values from the file.
'Check if an External Environment file is loaded and if not, load it.
fileName = Environment.ExternalFileName
If (fileName = "") Then
       Environment.LoadFromFile("C:\Environment.xml")
End If
'display value of one of the Environment variables from the External file
msgbox Environment("MyVarName")

LoadFromFile Method

Description
Loads the specified environment variable file. The environment variable file must be an XML file using the following syntax:
       
              This is the first variable's name
              This is the first variable's value
       
Note: You can also continue to use your QuickTest Professional 6.5 environment files (.ini format).
For more information about environment variable files, refer to the QuickTest Professional User's Guide.
Syntax
Environment.LoadFromFile(Path)
Argument
Type
Description
Path
String
The path of the environment file to load.
Example
The following example loads the MyVariables.xml file.
Environment.LoadFromFile("C:\QuickTest\Files\MyVariables.xml")

Value Property

Description
Sets or retrieves the value of environment variables. You can retrieve the value of any environment variable. You can set the value of only user-defined, environment variables.
Syntax
To set the value of a user-defined, environment variable:
Environment.Value(VariableName) = NewValue
To retrieve the value of a loaded environment variable:
CurrValue = Environment.Value (VariableName)
Argument
Type
Description
VariableName
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.
Example
The following example creates a new internal user-defined variable named MyVariable with a value of 10, and then retrieves the variable value and stores it in the MyValue variable.
Environment.Value("MyVariable")=10
MyValue=Environment.Value("MyVariable")
Note: You could omit the word Value in the statement above, because Value is the default property for the Environment object.

Environment Object

Description
Enables you to work with environment variables.
You can set or retrieve the value of environment variables using the Environment object. You can retrieve the value of any environment variable. 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
VariableName
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.
Example
The following example creates a new internal user-defined variable named MyVariable with a value of 10, and then retrieves the variable value and stores it in the MyValue variable.
Environment.Value("MyVariable")=10
MyValue=Environment.Value("MyVariable")

Understanding QuickTest Professional Terminology

The following terminology, specific to QuickTest Professional, is used in this help file:
Keyword View—A Keyword View enables tests and components to be created, viewed, and debugged using a keyword-driven, modular, table format. QuickTest automatically modifies the columns and options in the Keyword View to suit the specific needs of the document type (test or component) on which you are currently working.
Steps—A step represents an operation to be performed. QuickTest provides keywords that help you define steps quickly and easily.
The following terminology, specific to business components, is used in this guide:
Business Component (or Component)An easily-maintained, reusable unit comprising one or more steps that perform a specific task. Business components may require input values from an external source or from other components, and they can return output values to other components.
Business Process Test—A scenario comprising a serial flow of business components, designed to test a specific business process of an application.
Component Input Parameters—Variable values that a business component can receive and use as the values for specific, parameterized steps in the component. A component parameter may be accessed by any component in the Quality Center project.
Component Output Parameters—Values that a business component can return. These values can be viewed in the business process test results and can also be used as input for a component that is used later in the test. A component parameter may be accessed by any component in the Quality Center project.
Local Input Parameters—Variable values that an operation or a business component step can receive and use as the values for specific, parameterized steps in the component. A local parameter can only be accessed by the component in which it defined.
Local Output Parameters—Values that an operation or a business component step can return. These values can be viewed in the business process test results and can also be used as input for a later step in the component. A local parameter can only be accessed by the component in which it defined.
QuickTest Engineer—An expert in QuickTest Professional automated testing. The QuickTest Engineer defines and manages the resources that are needed to create and work with business components. The QuickTest Engineer creates application areas that specify all of the resources and settings needed to enable Subect Matter Experts to create business components and business process tests in Quality Center. The QuickTest Engineer can create and modify function library files (such as VBScript library files), and populate the shared object repository with test objects that represent the different objects in the application being tested. The QuickTest Engineer can also create and debug business components in QuickTest.
Roles—The various types of users who are involved in Business Process Testing.
Subject Matter Expert—A person who has specific knowledge of the application logic, a high-level understanding of the entire system, and a detailed understanding of the individual elements and tasks that are fundamental to the application being tested. The Subject Matter Expert uses Quality Center to create business components and business process tests.

Parameterizing Input Values

In the Value cell, you can parameterize input values for a step using local or component parameters.
To parameterize an input value using a local parameter:
  1. In the Value cell, click the parameterization button  or press Ctrl + F11. The Value Configuration Options dialog box opens.
    Note: If at least one input component parameter is defined in the component, the default input type is Component parameter and the default input name is the first output parameter displayed in the Parameters tab of the Business Component Settings dialog box.
  2. In the Parameter box, select Local parameter. The details for the local parameter type are displayed.

  3. Specify the property details for the local parameter:
    • Name—Enter a meaningful name for the parameter or choose one from the list.
    • Value—Enter an input value for the parameter. If you do not specify a value, QuickTest assigns a default value, as follows:
Value Type
QuickTest Default Value
String
Empty string
Boolean
True
Date
The current date
Number
0
Password
Empty string
    • Description—Enter a brief description for the parameter.
  1. Click OK. The local parameter is displayed in the Value cell of your step. When the component is run, it will use the value specified in the parameter for the step.
Tips: You can cancel the parameterization of a value by selecting the Constant option in the Value Configuration Options dialog box and entering a constant value.
If you click in the Value cell after you define a local parameter for it, the  icon is displayed in each part of the cell for which a local parameter is defined.
To parameterize an input value using a component parameter:
  1. In the Value cell, click the parameterization button  or press Ctrl + F11. The Value Configuration Options dialog box opens.
Note: If at least one input component parameter is defined in the component, the default input type is Component parameter and the default input name is the first output parameter displayed in the Parameters tab of the Business Component Settings dialog box.
If no component parameter is defined, you must define one before you can use it to parameterize an input value. For more information, see Defining Parameters for Your Component.
  1. In the Name box, select the component parameter you want to use for the parameterized value. The details for the component parameter are displayed as read-only.

  2. Click OK. The component parameter is displayed in the Value cell of your step. When the component is run, it will use the value specified in the parameter for the step.
Tips: You can cancel the parameterization of a value by selecting the Constant option in the Value Configuration Options dialog box and entering a constant value.
If you click in the Value cell after you define a component parameter for it, the  icon is displayed in each part of the cell for which a component parameter is defined.

Parameterizing Output Values

You can parameterize output values for a step using local or component parameters, in the step Output cell. You can then use the output parameter value as an input value in a later step in the component, or in a later component in the business process test.
To parameterize an output value using a local parameter:
  1. In the Output cell, click the output value button  or press Ctrl + F11. The Output Options dialog box opens.
Note: If at least one output component parameter is defined in the component, the default output type is Component parameter and the default output name is the first output parameter displayed in the Parameters tab of the Business Component Settings dialog box.
  1. In the Output Types box, select Local parameter. The details for the local parameter type are displayed.

  2. Specify the property details for the local parameter:
    • Name—Enter a meaningful name for the parameter or choose one from the list.
    • Description—Enter a brief description for the parameter.
  3. Click OK. The local parameter is displayed in the Output cell of your step. When the component is run, it will output the value to the output parameter specified for the step.
Tip: If you click in the Output cell after you define a local parameter for it, the  icon is displayed in each part of the cell for which a local parameter is defined.
To parameterize an output value using a component parameter:
  1. In the Output cell, click the output value button  or press Ctrl + F11. The Output Options dialog box opens.
Note: If at least one output component parameter is defined in the component, the default output type is Component parameter and the default output name is the first output parameter displayed in the Parameters tab of the Business Component Settings dialog box.
If no component parameter is defined, you must define one before you can use it to parameterize an output value. For more information, see Defining Parameters for Your Component.
  1. In the Name box, select the component parameter in which to store the output value. The details for the component parameter are displayed as read-only.
  2. Click OK. The component parameter is displayed in the Output cell of your step. When the component is run, it will output the value to the output parameter specified for the step.
Tip: If you click in the Value cell after you define a local parameter for it, the  icon is displayed in each part of the cell for which a local parameter is defined.

Item Property

Description
Retrieves the current value of the specified Parameter object.
Syntax
Val=Parameter(ParamName).Item
Argument
Type
Description
ParamName
String
The name of the action, or component parameter for which you want to retrieve the value.
Val
Variant
The location in which you want to store the retrieved value.
Example
The following example uses the Item property to retrieve the current value of the Axn1_in2 input parameter.
CurrVal=Parameter(Axn1_in2).Item

PathFinder Object

Description
Enables you to find file paths.

Locate Method

Description
Returns the full file path that QuickTest uses for the specified relative path (resolves the path) based on the folders specified in the Folders tab search list (Tools > Options > Folders tab) of the Options dialog box.
For more information on the Folders search list, refer to the QuickTest Professional User's Guide.
Syntax
PathFinder.Locate (RelativePath)
Argument
Type
Description
RelativePath
String
The relative path you want to resolve.
Return Value
String
Example
The following example uses the Locate method to find the path in which the MyEnvFile.txt file is located.
y=PathFinder.Locate ("MyEnvFile.txt")
 
 

QCUtil Object

Description
The object used to access the Quality Center Open Test Architecture (OTA) interface. You can use the properties associated with the QCUtil object to return Quality Center OTA objects. You can use the returned object to perform any OTA property or method supported for that object. For information on the objects, properties, and methods supported for the returned objects exposed by the QCUtil object, refer to the Quality Center Open Test Architecture Guide.
Note: This object replaces the TDUtil object used in version of QuickTest 6.5 and earlier. The TDUtil object is supported for backwards compatibility only. It is recommended to update your tests and components to use the QCUtil object.

CurrentRun Property

Description
Returns the Quality Center OTA Run object, which represents the current run. For more information, refer to the Quality Center Open Test Architecture Guide.
Note: This property is supported only when QuickTest is connected to Quality Center, version 7.5 or later and the run results location is a Quality Center location.
Syntax
QCUtil.CurrentRun
Return Value
A Quality Center OTA Run object.
Example
This example returns the current test run results and reports the Quality Center run name to the QuickTest test results.
dim CurrentRun
set CurrentRun = QCUtil.CurrentRun
Reporter.ReportEvent 2,"Current Run", CurrentRun.Name

CurrentTest Property

Description
Returns the Quality Center OTA Test object, which represents a planning test. For more information, refer to the Quality Center Open Test Architecture Guide.
Note: This property is supported only when QuickTest is connected to Quality Center and the test is saved in a Quality Center project.
Syntax
QCUtil.CurrentTest
Return Value
A Quality Center OTA Test object.
Example
This example returns the planning test and reports its name to the test results.
dim CurrentTest
set CurrentTest = QCUtil.CurrentTest
Reporter.ReportEvent 2,"Current Test", CurrentTest.Name

CurrentTestSet Property

Description
Returns the Quality Center OTA TestSet object, which represents a group of tests. For more information, refer to the Quality Center Open Test Architecture Guide.
Note: This property is supported only when QuickTest is connected to Quality Center and the run results location is a Quality Center location.
Syntax
QCUtil.CurrentTestSet
Return Value
A Quality Center OTA TestSet object.
Example
This example returns the test set of the current test run and reports its name to the test results.
dim CurrentTSTest
set CurrentTSTest = QCUtil.CurrentTestSet
Reporter.ReportEvent 2,"Current TestSet", CurrentTSTest.Name

CurrentTestSetTest Property

Description
Returns the Quality Center OTA TSTest object, which represents an execution instance. For more information, refer to the Quality Center Open Test Architecture Guide.
Note: This property is supported only when QuickTest is connected to Quality Center.
Syntax
QCUtil.CurrentTestSetTest
Return Value
A Quality Center OTA TSTest object.
Example
This example returns the execution test and reports its name to the test results.
Dim CurrentTSTestSet
set CurrentTSTestSet = QCUtil.CurrentTestSetTest
Reporter.ReportEvent 2,"Current TestSet Test", CurrentTSTestSet.Name

IsConnected Property

Description
Indicates whether QuickTest is currently connected to a Quality Center project.
Note: Returns False if QuickTest is connected to a Quality Center server, but not connected to any project.
Tip: It is recommended to insert an IsConnected step before other Quality Center operations.
Syntax
QCUtil.IsConnected
Return Value
Boolean
Example
This example checks whether QuickTest is currently connected to a Quality Center project. If it is, then it reports information about the current server, project, and domain name to the test results. Otherwise it reports a message that QuickTest is not connected to Quality Center.
if QCUtil.IsConnected then
       Reporter.ReportEvent 0, "Connected", "Connected to server: " + QCUtil.TDConnection.ServerName + chr (13) +"Project: " + QCUtil.TDConnection.ProjectName + chr (13) + "Domain: " + QCUtil.TDConnection.DomainName
else
Reporter.ReportEvent 1, "Not connected", "Not connected to Quality Center"
end if

TDConnection Property

Description
Returns the Quality Center OTA TDConnection object, which represents the current Quality Center session and provides access to the Quality Center object model.
For more information, refer to the Quality Center Open Test Architecture Guide.
Note: This property is supported only when QuickTest is connected to Quality Center.
Syntax
QCUtil.TDConnection
Return Value
The Quality Center OTA TDConnection object.
Example
This example reports a defect to the Quality Center database and enters values for the Status, Summary and Dectected By fields.
Dim TDConnection
Set TDConnection = QCUtil.TDConnection
'Get the IBugFactory
Set BugFactory = TDConnection.BugFactory
'Add a new, empty defect
Set Bug = BugFactory.AddItem (Nothing)
'Enter values for required fields
Bug.Status = "New"
Bug.Summary = "New defect"
Bug.DetectedBy = "admin" ' user that must exist in the database's user list
'Post the bug to the database ( commit )
Bug.Post

RandomNumber Object

Description
Enables you to work with random number parameters.
You can generate a value for the specified random number parameter using the RandomNumber object.
Syntax
RandomNumber(ParameterNameOrStartNumber [,EndNumber])
Argument
Type
Description
ParameterName or StartNumber
Variant
You can specify two different types of values for this options:
ParameterName—the name of a random number parameter that has already been defined in the Parameter Options or Value Configuration Options dialog box
StartNumber— the start number for the range within which the random number is generated.
EndNumber
Number
Relevant only when you specify a start number for the first argument.
The end number for the range within which the random number is generated. Maximum allowable value is 2147483647.
Example
The following example generates a random number between 0 and 100.
x=RandomNumber (0,100)
The following example generates a random number using the random number settings defined in the MyRandom parameter.
x=RandomNumber("MyRandom")
Note: The above example works only if you have already defined a Random Number parameter called MyRandom in the Parameter Options or Value Configuration Options dialog box. For more information on defining random number parameters in these dialog boxes, refer to the QuickTest Professional User's Guide.

Value Property

Description
Generates a value for the specified RandomNumber parameter.
Syntax
To generate any random number:
RandomNumber.Value(ParameterNameOrStartNumber [,EndNumber])
Argument
Type
Description
ParameterName or StartNumber
Variant
You can specify two different types of values for this options:
ParameterName—the name of a random number parameter that has already been defined in the Parameter Options or Value Configuration Options dialog box
StartNumber— the start number for the range within which the random number is generated.
EndNumber
Number
Relevant only when you specify a start number for the first argument.
The end number for the range within which the random number is generated. Maximum allowable value is 2147483647.
Note: The Value property is the default property for the RandomNumber object. Thus you can also generate a random number as described in the RandomNumber Object syntax.
Example
The following example generates a random number between 0 and 100.
x=RandomNumber.Value(0,100)
The following example generates a random number using the random number settings defined in the MyRandom parameter.
x=RandomNumber.Value("MyRandom")

REPORTER EVENT

Filter Property

Description
Retrieves or sets the current mode for displaying events in the Test Results. You can use this method to completely disable or enable reporting of steps following the statement, or you can indicate that you only want subsequent failed or failed and warning steps to be included in the report.
Syntax
To retrieve the mode setting:
CurrentMode = Reporter.Filter
To set the mode:
Reporter.Filter = NewMode
The mode can be one of the following values:
Mode
Description
0 or  rfEnableAll
Default. All reported events are displayed in the Test Results.
1 or  rfEnableErrorsAndWarnings
Only event with a warning or fail status are displayed in the Test Results.
2 or  rfEnableErrorsOnly
Only events with a fail status are displayed in the Test Results.
3 or  rfDisableAll
No events are displayed in the Test Results.
Example
The following example uses the Filter method to report the following events in the Test Results: 1, 2, 5, and 6.
Reporter.ReportEvent micGeneral, "1", ""
Reporter.ReportEvent micGeneral, "2", ""
Reporter.Filter = rfDisableAll
Reporter.ReportEvent micGeneral, "3", ""
Reporter.ReportEvent micGeneral, "4", ""
Reporter.Filter = rfEnableAll
Reporter.ReportEvent micGeneral, "5", ""
Reporter.ReportEvent micGeneral, "6", ""

ReportEvent Method

Description
Reports an event to the test results.
Syntax
Reporter.ReportEvent EventStatus, ReportStepName, Details [, in]
Argument
Type
Description
EventStatus
Number or pre-defined constant
Status of the report step:
0 or micPass: Causes the status of this step to be passed and sends the specified message to the report.
1 or micFail: Causes the status of this step to be failed and sends the specified message to the report. When this step runs, the test or component fails.
2 or micDone: Sends a message to the report without affecting the pass/fail status of the test or component.
3 or micWarning: Sends a warning message to the report, but does not cause the test or component to stop running, and does not affect the pass/fail status of the test or component.
ReportStepName
String
Name of the intended step in the report (object name).
Details
String
Description of the report event. The string will be displayed in the step details frame in the report.
in
N/A
Not in use.
Example
The following examples use the ReportEvent method to report a failed step.
Reporter.ReportEvent 1, "Custom Step", "The user-defined step failed."
or
Reporter.ReportEvent micFail, "Custom Step", "The user-defined step failed."

ReportPath Property

Description
Retrieves the folder path in which the current test or component's results are stored.
Note: Do not use this property to attempt to set the results folder path.
Syntax
Path = Reporter.ReportPath
Argument
Type
Description
Path
String
The folder path in which the current test or component's results are stored.
Example
The following example uses the ReportPath method to retrieve the folder in which the results are stored and displays the folder in a message box.
dim Path
Path = Reporter.ReportPath
MsgBox (Path)

Services Object

Description
Enables you to control and monitor how your test runs in conjunction with LoadRunner, Astra LoadTest, or Business Process Monitor. For more information, refer to the specific product documentation.

Abort Method

Description
Stops the execution of the test.
Syntax
Services.Abort

AddWastedTime Method

Description
Specifies the wasted time for all open transactions.
Note: This method is supported only in conjunction with LoadRunner, Astra LoadTest, or Business Process Monitor. For more information, refer to the specific product documentation.
Syntax
Services.AddWastedTime (WastedTime)
Argument
Type
Description
WastedTime
Number
The amount of time you want to specify as wasted time for each transaction (in milliseconds).

EndTransaction Method

Description
Marks the end of a transaction for performance analysis.
Each transaction name should have an associated StartTransaction and EndTransaction. The StartTransaction statement must appear before the associated EndTransaction.
Note: A transaction can be inserted anywhere in your test, but must start and end within the same action.
Syntax
Services.EndTransaction Name [, Status]
Argument
Type
Description
Name
String
The name of the transaction.
Note: The following are illegal when specifying the name: spaces # , :
Status
Long
Optional. A constant or number that specifies the ending status of a transaction.
Pass (0) - default
Fail (1)
Example
The following statement indicates that transaction "trans1" ended with a status of passed.
Services.EndTransaction "trans1", Pass

GetEnvironmentAttribute Method

Description
Gets the test's environment properties.
Note: This method is supported only when the test runs in conjunction with LoadRunner and Astra LoadTest. For more information, refer to the specific product documentation.
Syntax
Services.GetEnvironmentAttribute(Attribute)
Example
Suppose you enter the following in the command line:
-OrderBook yes -NumOfPayments 24
The following example retrieves values set in the Controller command line and displays them in the log file.
bOrderBook = Services.GetEnvironmentAttribute("OrderBook")
Services.LogMessage (bOrderBook &"OrderBook")
nNumOfPayments = Services.GetEnvironmentAttribute("NumOfPayments")
Services.LogMessage ("NumOfPayments is "& nNumOfPayments)
For more information about passing a command line from the Controller to a script, refer to the Astra LoadTest Controller User's Guide.

IterationNumber Method

Description
Retrieves the current global iteration number of the test execution.
Syntax
Services.Iteration Number

LogMessage Method

Description
Sends a log message according to the appropriate level, as specified below.
Note: This method is supported only in conjunction with LoadRunner, Astra LoadTest, or Business Process Monitor. For more information, refer to the specific product documentation.
Syntax
Services.LogMessage Data [, Level]
Argument
Type
Description
Data
String
The message data.
Level
Long
Optional. Use one of the following constants or numbers to specify the message status and where it should be sent:
ErrorMsg (7) - set the test status to Fail and consider this an error message.
OutputMsg (6) - send the message to the standard Vuser log.
StatusMsg(51) - send the message to the Vuser Status field.
ExtendedMsg (16) - send the message to the Vuser log when the Extended filter is used.
Remarks
If you do not specify a level, the message is treated as OutputMsg.
Example
In the following example, the message sets the test status to fail, and appears as an error message.
Services.LogMessage "An error occurred", ErrorMsg

Rendezvous Method

Description
Sets a rendezvous point in the Vuser script.
Note: This method is supported only when the test runs in conjunction with LoadRunner, Astra LoadTest, or Business Process Monitor. For more information, refer to the specific product documentation.
Syntax
Services.Rendezvous Name
Argument
Type
Description
Name
String
The name of the rendezvous to be inserted in the script.

SetTransactionStatus Method

Description
Sets the status for all open transactions.
Note: This method is supported only in conjunction with LoadRunner, Astra LoadTest, or Business Process Monitor. For more information, refer to the specific product documentation.
Syntax
Services.SetTransactionStatus Status
Argument
Type
Description
Status
Long
A constant that specifies the ending status of a transaction.
Pass (0)
Fail (1)

StartTransaction Method

Description
Marks the beginning of a transaction for performance analysis.
Each transaction name should have an associated StartTransaction and EndTransaction. The StartTransaction statement must appear before the associated EndTransaction.
Note: A transaction can be inserted anywhere in your test, but must start and end within the same action.
Syntax
Services.StartTransaction Name
Argument
Type
Description
Name
String
The name of the transaction.
Note: The following are illegal when specifying the name: spaces # , :
Example
The following statement opens a transaction called "trans1."
Services.StartTransaction "trans1"

ThinkTime Method

Description
Pauses the execution during a test run to simulate the time a real user pauses between actions.
Syntax
Services.ThinkTime Seconds
Argument
Type
Description
Seconds
real number
The number of seconds to pause the test during execution.

UserDataPoint Method

Description
Records a user-defined data sample for analysis.
Note: This method is supported only in conjunction with LoadRunner, Astra LoadTest, or Business Process Monitor. For more information, refer to the specific product documentation.
Syntax
Services.UserDataPoint Value, Name
Argument
Type
Description
Value
Double
The value to record.
Name
String
The label of the data point as it appears on the graph.
Example
The following statement gathers the price of a product each time the test executes the step and puts the price in the Data Table column labeled "Price_P". Once the test executes the step numerous times (for example, in a loop), the data points appear on a graph where the price is labeled "Price."
Services.UserDataPoint DataTable("Price_P"), "Price"

Setting Object

Description
Enables you to modify test settings during the test run. The settings are a dictionary of keys and their values, to be used as global variables.

Add Method

Description
Adds and sets a user-defined run-time setting.
Syntax
Setting.Add SettingName, SettingValue
Argument
Type
Description
SettingName
String
Assigns a name to the new run-time setting.
SettingValue
String
Assigns a value to the new run-time setting.
Example
The following example uses the Add method to create a new setting called "TesterName", assigns the value "JohnSmith" to the setting, and writes the value of the setting to the report.
Setting.Add "TesterName","JohnSmith"
Tester = Setting("TesterName")
Reporter.ReportEvent 1, "The tester is", Tester.

Exists Method

Description
Determines if a key exists in the dictionary.
Syntax
Setting.Exists(Key)
Argument
Type
Description
Key
String
The name of the key to check.
Example
The following example checks to see if the IterNumber key exists. If it doesn't exist, it adds it to the dictionary and assigns the value 1. If it already exists, it increments the value.
If Not Setting.Exists("IterNum") then
Setting.Add "IterNum", 1 'create "IterNum" and assign to 1
else
Setting.Item("IterNum")=Setting.Item("IterNum")+1 'increment "IterNum"
end if

Remove Method

Description
Removes a user-defined run-time setting.
Syntax
Setting.Remove SettingName
Argument
Type
Description
SettingName
String
The name of the run-time setting.
Example
The following example uses the Remove method to remove the "TesterName" setting.
Setting.Remove "TesterName"

Item Property

Description
Sets or retrieves the value of a given key from the dictionary.
Syntax
Setting.Item(Key)
Value Name
Type
Description
Key
String
The name of the object's key.
Example
The following example checks to see if the IterNumber key exists. If it doesn't exist, it adds it to the dictionary and assigns the value 1. If it already exists, it uses the item property of the setting object, and increments the iteration value.
With Setting
If Not .Exists("IterNumber") then
       .Add "IterNumber",1
Else
       .Item("IterNumber")=.Item("IterNumber")+1
End if
End With
SystemUtil Object
Description
An object used to open and close applications and processes during a run session.
Operations
    Methods

Closes all processes opened by QuickTest.
Syntax :-object.CloseDescendentProcesses
Return Type
A Long value.  The number of instances of the application that are closed when the statement runs.
Sub CloseDescendentProcesses_Example()
'Suppose that the Record and Run dialog box opens a Windows Explorer window
'at the beginning of a test run, and then the statement below opens a
'Notepad window. In this case the message box statement below displays 2.


SystemUtil.Run "Notepad.exe"
MsgBox SystemUtil.CloseDescendentProcesses

End Sub


Closes a process that is the owner of a window with the specified handle.
Syntax
object.CloseProcessByHwnd (hWnd)
Argument
Description
object
A test object of type SystemUtil.
hWnd
Required. An ULong object.
The handle of the window owned by the process you want to close.
Tip: You can retrieve the window handle using the hwnd property.  For example:
Window("MyAppName").GetROProperty("hwnd")
Return Type
A Boolean value.  
·         True--The specified process was successfully closed.
·         False--The specified process was not closed.
Example: Close the Process that is an Owner of a Window with the Specified Handle

 

Sub CloseProcessByHwnd_Example()
'The following example retrieves the handle of the Notepad window, and then
'uses the CloseProcessByHwnd method to close the notepad application.

hWnd = Window("Notepad").GetROProperty("hwnd")
SystemUtil.CloseProcessByHwnd (hWnd)

End Sub


CloseProcessById
Closes a process according to its Process ID (PID).
Syntax
object.CloseProcessById (wdProcessId)
Argument
Description
object
A test object of type SystemUtil.
wdProcessId
Required. An ULong object.
The Process ID (PID) of the process you want to close.
Tip: You can find the PID of an application by viewing the value in the Processes tab of the Windows Task Manager, or you can retrieve the value using the process id property.  For example:
Window("MyAppName").GetROProperty("process id")
Return Type
A Boolean value.  
·         True--The specified process was successfully closed.
·         False--The specified process was not closed.
Example: Close an Application According to its Process ID

 

Sub CloseProcessById_Example()

'The following example retrieves the process ID of the Notepad window, and then
'uses the CloseProcessByID method to close the notepad application.

PID = Window("Notepad").GetROProperty("process id")
    SystemUtil.CloseProcessById (PID)


End Sub



Closes a process according to its name.
Remarks
If multiple processes exist with the same name, they are all closed.
Syntax
object.CloseProcessByName (bsProcessName)
Argument
Description
object
A test object of type SystemUtil.
bsProcessName
Required. A String value.
The name of the process you want to close.
Return Type
A Long value.  The number of instances of the application that are closed when the statement runs.
Example: Close All Instances of a Specified Application

 

Sub CloseProcessByName_Example()
'The following example uses the CloseProcessByName method to close any open
'instances of Notepad. If the only instances of Notepad that are open are
' those opened by the statements below, then the MsgBox displays 3.

SystemUtil.Run "Notepad.exe"
SystemUtil.Run "Notepad.exe"
SystemUtil.Run "Notepad.exe"
MsgBox SystemUtil.CloseProcessByName("Notepad.exe")


End Sub



Closes all processes that are owners of windows with the specified title.
Syntax
object.CloseProcessByWndTitle (bsTitle, [bRegExp])
Argument
Description
object
A test object of type SystemUtil.
bsTitle
Required. A String value.
The title of the window owned by the process you want to close.
bRegExp
Optional. A Boolean value.
Indicates whether the bsTitle argument is treated as a regular expression.  Default = False.
Return Type
A Long value.  The number of instances of the application that are closed when the statement runs.
Example 1: Close All Windows with a Title Containing a Specified String

 

Sub CloseProcessByWndTitle_Example1()
'The following example closes all top-level windows with a titlebar that contains the
'string "Notepad", by specifying "Notepad" as a regular expression.

SystemUtil.CloseProcessByWndTitle "Notepad", True

End Sub


Example 2: Close All Windows in which the Exact Title Matches a Specified String

 

Sub CloseProcessByWndTitle_Example2()
'The following example closes all top-level windows with the exact title: "Untitled - Notepad".
'The title tring is treated as a literal string.

SystemUtil.CloseProcessByWndTitle "Untitled - Notepad"

End Sub



Runs a file or application
Remarks
When specifying a non-executable file, the file opens in the associated application.
Note: A SystemUtil.Run statement is automatically added to your test when you run an application from the Start menu or the Run dialog box while recording a test.
Tip: You can also use this method to perform operations on the specified file, similar to the usage of the Windows ShellExecute command.

Syntax
object.Run file, [params], [dir], [op], [mode]
Argument
Description
object
A test object of type SystemUtil.
file
Required. A String value.
The name of the file you want to run.
params
Optional. A String value.
If the specified file argument is an executable file, use the params argument to specify any parameters to be passed to the application.
dir
Optional. A String value.
The default directory of the application or file.
op
Optional. A String value.
The action to be performed. If this argument is blank ( ""), the open operation is performed.
The following operations can be specified for the op argument:

Operation
Description
open      -         pens the file specified by the FileName parameter. The file can be an executable file, a document file, or a folder. Non-executable files are open in the associated application.
edit        -         Launches an editor and opens the document for editing. If the FileName argument does not specify an editable document file, the statement fails.
explore             -          xplores the folder specified by the FileName argument.
find        -        Initiates a search starting from the specified folder path.
print       -         Prints the document file specified by the FileName argument. If the specified file is not a printable document file, the statement fails.

mode
Optional. An Integer value. Specifies how the application is displayed when it opens. You can specify one of the modes in the table below. Default = 1
Mode
Description
1  -       Activates and displays the window. If the window is minimized or maximized, the system restores it to its original size and position. Specify this flag when displaying the window for the first time.
2  -       Activates the window and displays it as a minimized window.
3  -       Activates the window and displays it as a maximized window.
4  -       Displays the window in its most recent size and position. The active window remains active.
5  -       Activates the window and displays it in its current size and position.
6  -       Minimizes the specified window and activates the next top-level window in the Z order.
7  -       Displays the window as a minimized window. The active window remains active.
8  -       Displays the window in its current state. The active window remains active.
9  -       Activates and displays the window. If the window is minimized or maximized, the system restores it to its original size and position. Specify this flag when restoring a minimized window.
10  -     Sets the show-state based on the state of the program that started the application.

Return Type
None  
Example: Open a Text File in the Default Text Application (Notepad)

 

Sub CloseDescendentProcesses_Example()
'The following example uses the Run method to open a file named type.txt
'in the default text application (Notepad). It then types "happy days",
'saves the file using shortcut keys, and then closes the application.

SystemUtil.Run "C:\type.txt", "", "", ""
Window("Text:=type.txt - Notepad").Type "happy days"
Window("Text:=type.txt - Notepad").Type micAltDwn & "F" & micAltUp
Window("Text:=type.txt - Notepad").Type micLShiftDwn & "S" & micLShiftUp
Window("Text:=type.txt - Notepad").Close

End Sub




TextUtil Object

Description
The object used to recognize text within a specified window handle.

GetText Method

Description
Returns the text from the specified window handle area. The area is defined by pairs of coordinates that designate two diagonally opposite corners of a rectangle.
Notes:
This method is supported for backward compatibility only. This means that support is available only for tests using this method that were created in QuickTest 6.5 or earlier and only when exactly the same conditions (i.e. operating system, application, and hardware versions) are used for the run as were used when the step was created.
You can also retrieve the text of a specified area using the following syntax: TestObject(description).GetVisibleText [Left, Top, Right, Bottom].
Syntax
TextUtil.GetText(hWnd [, Left, Top, Right, Bottom])
Argument
Type
Description
hWnd
Number
The handle to a run-time object's window.
Note: If hWnd is not 0, then the coordinates apply to the specified window. If hWnd is 0, the coordinates apply to the screen.
Left, Top, Right, Bottom
Number
Optional. These arguments define the search area within the window or screen.
Note: If these arguments are not specified, the method returns all text contained in the window or screen.
Return Value
String
Example
The following example retrieves all of the text from the "Telnet" window.
' Find handle of the Telnet window
Extern.Declare micLong,"FindWindow","User32","FindWindowA",micString,micString
hTelnet = Extern.FindWindow("TelnetWClass", "Telnet - 100.100.100.100")
' Get text from the Telnet window
TelnetText = TextUtil.GetText(hTelnet)
MsgBox TelnetText
The following example retrieves the text from the screen rectangle.
' Get text from the screen rectangle
MsgBox TextUtil.GetText(0, 20, 20, 200, 200)

GetTextLocation Method

Description
Checks whether a specified text string is contained in a specified window area. If the text string is located, the location coordinates are also returned.
Notes:
This method is supported for backward compatibility only. This means that support is available only for tests using this method that were created in QuickTest 6.5 or earlier and only when exactly the same conditions (i.e. operating system, application, and hardware versions) are used for the run as were used when the step was created.
You can also check whether a specified text string is contained in a specified window area using the following syntax: TestObject(description).GetTextLocation (TextToFind, Left, Top, Right, Bottom [, MatchWholeWordOnly]).
Syntax
TextUtil.GetTextLocation(TextToFind, hWnd, Left, Top, Right, Bottom[, MatchWholeWordOnly])
Argument
Type
Description
TextToFind
String
The text string you want to locate.
hWnd
Number
The handle to a run-time object's window.
Note: If hWnd is not 0, then the coordinates apply to the specified window. If the hWnd is 0, the coordinates apply to the screen.
Left, Top, Right, Bottom
InOut, Number
These arguments define the search area within the window or screen. Set all coordinates to -1 to search for the text string within the entire window or screen. The method returns the coordinates of the rectangle containing the first instance of the text into these variables if the text is found.
MatchWholeWordOnly
Boolean
Optional. If True, the method searches for occurrences that are whole words only and not part of a larger word. If False, the method does not restrict the results to occurrences that are whole words only.
Default value = True
Return Value  -
Boolean
Example
The following example searches for the word Mercury within the entire screen and clicks it if the word is found.
l = -1
t = -1
r = -1
b = -1
Succeeded = TextUtil.GetTextLocation("16",0,l,t,r,b)
If Not Succeeded Then
       MsgBox "Text not found"
else
       x = (l+r) / 2
       y = (t+b) / 2
       Set dr = CreateObject("Mercury.DeviceReplay")
       dr.MouseClick x, y, 0
End If

TSLTest Object

Description
Enables you to run WinRunner tests and call WinRunner functions from QuickTest. For additional information on running WinRunner tests from QuickTest, refer to the QuickTest Professional User's Guide.

CallFunc Method

Description
Enables you to call a TSL function in a WinRunner compiled module from QuickTest. For more information on TSL and WinRunner compiled modules, refer to the WinRunner User's Guide.
Note: This method is supported only when WinRunner version 7.01 or later is installed on the computer running the QuickTest test or component.
This method was used in QuickTest Professional version 6.0, and is supported primarily for backward compatibility only. It is recommended to use the newer CallFuncEx method when working with WinRunner version 7.6 or later.
Syntax
TSLTest.CallFunc ModulePath, Function [, Parameters ]
Argument
Type
Description
ModulePath
String
The path of the WinRunner compiled module.
Function
String
The function from the compiled module (or any TSL function) to call.
Parameters
String
Optional. Up to 8 WinRunner test parameters.
Example
In the following example, QuickTest calls the "MessageBoxA" function, defined in the Windows API module that resides in the lib\win32api folder in the WR installation directory. This function creates a message box whose caption is its third parameter and whose text string is its second parameter.
TSLTest.CallFunc "C:\Program Files\Mercury Interactive\WinRunner
\lib\win32api", "MessageBoxA", "0", "The function MessageBoxA from user32 works correctly.", "MessageBoxA function", "3"

CallFuncEx Method

Description
Enables you to call a TSL function in a WinRunner compiled module from QuickTest. For more information on TSL and WinRunner compiled modules, refer to the WinRunner User's Guide.
Note: This method is supported only when WinRunner version 7.6 or later is installed on the computer running the QuickTest test or component.
Syntax
TSLTest.CallFuncEx ModulePath, Function, RunMinimized, CloseApp [, Parameters ]
Argument
Type
Description
ModulePath
String
The path of the WinRunner compiled module.
Function
String
The function from the compiled module (or any TSL function) to call.
RunMinimized
Boolean
Indicates whether to open and keep WinRunner minimized while running the WinRunner function.
CloseApp
Boolean
Indicates whether to close the WinRunner application when the WinRunner function run ends.
Parameters
String
Optional. Up to 15 WinRunner test parameters.
Return Value
Variant. The return value of the called function.
Examples
In the following example, QuickTest calls the "MessageBoxA" function, defined in the Windows API module that resides in the lib\win32api folder in the WR installation directory. This function creates a message box whose caption is its third parameter and whose text string is its second parameter. WinRunner is visible (not minimized) while the function runs, and closes when the function run ends.
TSLTest.CallFuncEx "C:\Program Files\Mercury Interactive\WinRunner
\lib\win32api", "MessageBoxA", False, True, "0", "The function MessageBoxA from user32 works correctly.", "MessageBoxA function", "3"
The following examples uses the CallFuncEx method to call a WinRunner function and retrieve the return value of the called function.
dim RC
RC = TSLTest.CallFuncEx ("J:\WR\TESTS\QTP_INTEGRATION\WR_LIB\wr_custom_functions","_10parameters",True,False, "1", "2", "3", "4", "5", "6", "7", "8", "9", "10")
Reporter.ReportEvent 0,rc,rc

RunTest Method

Description
Enables you to run a WinRunner test from QuickTest. For more information on running WinRunner tests from QuickTest, refer to the QuickTest Professional User's Guide.
Note: This method is supported only when WinRunner version 7.01 or later is installed on the computer running the QuickTest test or component.
This method was used in QuickTest Professional version 6.0, and is supported primarily for backward compatibility only. It is recommended to use the newer RunTestEx method when working with WinRunner 7.6 or later.
Syntax
TSLTest.RunTest TestPath, TestSet [, Parameters ]
Argument
Type
Description
TestPath
String
The path of the WinRunner test.
TestSet
String
The test set within Quality Center, in which test runs are stored. Note that this argument is relevant only when working with a test in a Quality Center project. When the test is not saved in Quality Center, this parameter is ignored.
Parameters
String
Optional. Up to 8 WinRunner function argument.
Example
In the following example, QuickTest runs the test1 WinRunner test.
TSLTest.RunTest "D:\test1", ""

RunTestEx Method

Description
Enables you to run a WinRunner test from QuickTest. For more information on running WinRunner tests from QuickTest, refer to the QuickTest Professional User's Guide.
Note: This method is supported only when WinRunner version 7.6 or later is installed on the computer running the QuickTest test or component.
Syntax
TSLTest.RunTestEx TestPath, RunMinimized, CloseApp [, Parameters ]
Argument
Type
Description
TestPath
String
The path of the WinRunner test.
RunMinimized
Boolean
Indicates whether to open and keep WinRunner minimized while running the WinRunner test.
CloseApp
Boolean
Indicates whether to close the WinRunner application when the WinRunner test run ends.
Parameters
String
Optional. Up to 15 WinRunner function argument.
Example
In the following example, QuickTest runs the basic_flight WinRunner test and sends MyValue as the test's first (and only) parameter value. WinRunner opens in minimized mode. When the WinRunner test run ends, WinRunner remains open.
TSLTest.RunTestEx "C:\WinRunner\Tests\basic_flight", True, False, "MyValue"

XMLUtil Object

Description
The object used to access and return XML objects

CreateXML Method

Description
Creates and returns an object of type XMLData. If a root name is specified, a new, empty document is created.
Syntax
XMLUtil.CreateXML ( [RootName] )
Argument
Type
Description
RootName
String
Optional. The name of the new XML document. This can be either a relative path or a Quality Center path.
Example
The following example creates an XML object and uses it to load an XML file.
Set XMLObj = XMLUtil.CreateXML()
XMLObj.LoadFile("C:\XML\BookStore.xml")

CreateXMLfromFile Method

Description
Creates and returns an object of type XMLData.
Syntax
XMLUtil.CreateXMLFromFile( XMLFilePath)
Argument
Type
Description
XMLFilePath
String
The path of the XML file to load. This can be either a relative path or a Quality Center path.
Example
The following example creates an XML object and loads the XML file BookStore.xml into it.
Set XMLObj = XMLUtil.CreateXMLFromFile("C:\XML\BookStore.xml")


Comments

Popular posts from this blog

Convert JSON to XML using QTP/UFT/VBScript

Sample Code : Dim strPage,strJSON,objIE strPage = "C:\Jay\JLoader.html" Set objIE = CreateObject("InternetExplorer.Application") objIE.Visible = True objIE.Navigate2 strPage While objIE.Busy : Wend strJSON = "{""FirstName"":""Jay"", ""LastName"":""Krishna""}" Set objWin = objIE.document.parentWindow objWin.execScript "var jsonStr2XML = function(strJSON) { return json2xml(JSON.parse(strJSON));};" Msgbox  oWin.jsonStr2XML(strJSON) objIE.Quit In Detail: Converting The most popular data interchange format JSON(JavaScript Object Notation) to XML using QTP/UFT. Parsing JSON in UFT could be a challenge so we will use JavaScript in UFT to make it perfect. SO We need :              Java Script API  - To Convert JSON to XML                         JavaScript Files :                         http://goessner.net/download/prj/jsonxml/j

Read Outlook mail attachment and Body using Vb Script or QTP

Set olApp = CreateObject("Outlook.Application") Set olns = olApp.GetNameSpace("MAPI") Set ObjFolder = olns.GetDefaultFolder(6) j = 0 For each item1 in ObjFolder.Items        iattachCnt = item1.Attachments.Count     Print "Attachments Count: " & iattachCnt     For i = 1 to iattachCnt         Print "FileName :    " & item1.Attachments(i).FileName         Print "Display Name:   " & item1.Attachments(i).DisplayName         Print "Size: " & item1.Attachments(i).Size     Next     Print " Body : " & item1.body     Print "--------------------------------------Mail Num - " & j & " -----------------------------------------------"     j = j+1    Next

Excel Sorting By Rows and Columns

Excel Sorting By Row: Const xlAscending = 1 Const xlNo = 2 Const xlSortRows = 2 Set objExcel = CreateObject(“Excel.Application”) objExcel.Visible = True Set objWorkbook = objExcel.Workbooks.Open(“C:\Jay\Docs1.xls”) Set objWorksheet = objWorkbook.Worksheets(1) objWorksheet.Cells(1,1).activate Set objRange = objExcel.ActiveCell.EntireRow objRange.Sort objRange, xlAscending, , , , , , xlNo, , , xlSortRows set objExcel=nothing Excel Sorting By Column : Const xlAscending = 1′represents the sorting type 1 for Ascending 2 for Desc Const xlYes = 1 Set objExcel = CreateObject(“Excel.Application”)’Create the excel object objExcel.Visible = True’Make excel visible Set objWorkbook = _ objExcel.Workbooks.Open(“C:\Jay\Docs1.xls”)’Open the document Set objWorksheet = objWorkbook.Worksheets(1)’select the sheet based on the index .. 1,2 ,3 … Set objRange = objWorksheet.UsedRange’which select the range of the cells has some data other than blank Set objRange2 = objExcel.Range

How to Read or Select Context Menu or Right Click Menu using QTP.

Select The Item in Right Click Menu or Context Menu: Window("sampleWindow").WinMenu("MenuObjType:=1).Select"File;New" Here MenuObjtype can be 1 r 2 r 3 .......n Check wether the Item is Exist or Not: If Window("sampleWindow").WinMenu("MenuObjType:=1).GetItemProperty("1","Exist") Then   Msgbox"Exist" Else  Msgbox"Does Not Exist" End If                                         Or If Window("sampleWindow").WinMenu("MenuObjType:=1).GetItemProperty("File","Exist") Then   Msgbox"Exist" Else  Msgbox"Does Not Exist" End If Get the Items in Context Menu: For i = 1 to 10 Print  Window("sampleWindow").WinMenu("MenuObjType:=" & i).GetItemProperty("1","Label") Then Next

How to Download a file using VbScript

Following is the code to download a file using Vbscript, without using QTP This code uses the HTMLDom and URLDownloadToFile method from urlmon API. Since VBScript does support calling Native API methods directly, here I am using  Excel macro to declare a function for the urlmon API and running the macro by Excel API from VBscript Step1: Create a new excel and open the visual basic editor, Insert Module and paste the following code the Module, save the excel file Private Declare Function URLDownloadToFile Lib “urlmon” Alias _                                            “URLDownloadToFileA” ( _                                            ByVal pCaller As Long, ByVal szURL As String, _                                            ByVal szFileName As String, _                                            ByVal dwReserved As Long, _                                            ByVal lpfnCB As Long) As Long Sub FileSave(strUrl, Des)     r = URLDownloadToFile(0, strUrl, Des, 0, a)