Appendix A VBScript Functions and Keywords

This appendix contains a complete reference of functions and keywords in VBScript 5.6. You will also find a list of the VB/VBA functions and keywords that are not supported in VBScript. Where appropriate an alternative to an unsupported function or keyword is shown.s

Operators

An operator acts on one or more operands when comparing, assigning, concatenating, calculating, and performing logical operations.

Assignment Operator

The assignment operator is simply used for assigning a value to a variable or property. See the Set keyword for an explanation of how to reference and assign objects.

=

Name

Assignment

 

Description

Assigns the result of an expression, the value of a constant, or the value of another variable to a variable or property.

 

Syntax

Variable = value

Arithmetic Operators

The arithmetic operators are all used to calculate a numeric value, and are normally used in conjunction with the assignment operator and/or one of the comparison operators; they are listed in order of operator precedence.

^

Name

Exponentiation

 

Description

Raises a number to the power of an exponent.

 

Syntax

Result = number ^ exponentnumber and exponent is any valid numeric expression.

 

Example

MsgBox 5 ^ 5

MsgBox displays 3125, which is the result of raising the number 5 to the exponent 5.

*

Name

Multiplication

 

Description

Multiplies two numbers .

 

Syntax

Result = number1 * number2 number1 and number2 is any valid numeric expression.

 

Example

MsgBox 5 * 5

MsgBox displays 25, which is the result of multiplying the number 5 by 5.

/

Name

Floating-point division

 

Description

Returns a floating-point result when dividing two numbers.

 

Syntax

Result = number1/number2 number1 and number2 is any valid numeric expression.

 

Example

MsgBox 5 / 4

MsgBox displays 1.25, which is the result of dividing the number 5 by 4.

Name

Integer division

 

Description

Returns the integer part of the result when dividing two numbers.

 

Syntax

Result = number1 number2 number1 and number2 is any valid numeric expression.

 

Example

MsgBox 5 4

MsgBox displays 1, which is the integer part of the result, when dividing the number 5 with 4.

 

Notes

The numeric expressions are rounded to Byte , integer , or Long subtype expressions, before the integer division is performed. They are rounded to the smallest possible subtype; that is, a value of 255 will be rounded to a Byte , 256 will be rounded to an Integer , and so on.

Mod

Name

Modulus division

 

Description

Returns the remainder when dividing two numbers.

 

Syntax

Result = number1 Mod number2 number1 and number2 is any valid numeric expression.

 

Example

MsgBox 5 Mod 4 MsgBox displays 1, which is the remainder part of the result, when dividing the number 5 with 4.

 

Notes

The numeric expressions are rounded to Byte , Integer , or Long subtype expressions, before the modulus division is performed. They are rounded to the smallest possible subtype; that is, a value of 255 will be rounded to a Byte , 256 will be rounded to an Integer , and so on.

+

Name

Addition

 

Description

Sums two expressions.

 

Syntax

Result = expression1 + expression2 expression1 and expression2 is any valid numeric expression.

 

Example

MsgBox 5 + 5

MsgBox displays 10, which is the result of adding the expression 5 to 5.

 

Notes

If one or both expressions are numeric, the expressions will be summed, but if both expressions are strings, they will be concatenated . This is important to understand, especially if you have a Java background, in order to avoid runtime errors. In general, use the & operator (see under Concatenation Operators ) when concatenating, and the + operator when dealing with numbers.

-

Name

Subtraction

 

Description

Subtracts one number from another or indicates the negative value of an expression.

 

Syntax (1)

Result = number1 - number2 number1 and number2 is any valid numeric expression.

 

Example (1)

MsgBox 5 - 4

MsgBox displays 1, which is the result of subtracting the number 4 from 5.

 

Syntax (2)

-number number is any valid numeric expression.

 

Example (2)

MsgBox -(5 - 4)

MsgBox displays -1, which is the result of subtracting the number 4 from 5 and using the unary negation operator (-) to indicate a negative value.

Concatenation Operators

Concatenation operators are used for concatenating expressions; they are listed in order of operator precedence.

&

Name

Ampersand

 

Description

Concatenates two expressions.

 

Syntax

Returns the concatenated expressions.

Result = expression1 & expression2

 

Example

If expression1 is "WROX" and expression2 is " Press" then the result is "WROX Press" .

 

Notes

The expressions are converted to a String subtype, if they are not already of this subtype.

+

Name

+ Operator

 

Description

Does the same as the & operator if both expressions are strings.

 

Syntax

Returns the concatenated or summed expressions.

Result = expression1 + expression2

 

Example

1 + "1" = 2

"1" + "1" = "11"

 

Notes

If one or both expressions are numeric, the + operator will work as an arithmetic + operator and sum the expressions. A runtime error occurs if one expression is numeric and the other a string containing no numbers. It is recommended that + should be used only for numeric addition and never for concatenation purposes (use & instead).

Comparison Operators

The comparison operators are used for comparing variables and expressions against other variables , constants, or expressions; they are listed in order of operator precedence.

=

Name

Equal to

 

Description

Returns True if expression1 is equal to expression2; False otherwise .

 

Syntax

Result = expression1 = expression2

<>

Name

Not equal to

 

Description

Returns True if expression1 is not equal to expression2; False otherwise.

 

Syntax

Result = expression1 <> expression2

<

Name

Less than

 

Description

Returns True if expression1 is less than expression2; False otherwise.

 

Syntax

Result = expression1 < expression2

>

Name

Greater than

 

Description

Returns True if expression1 is greater than expression2; False otherwise.

 

Syntax

Result = expression1 > expression2

< =

Name

Less than or equal to

 

Description

Returns True if expression1 is less than or equal to expression2; False otherwise.

 

Syntax

Result = expression1 < = expression2

> =

Name

Greater than or equal to

 

Description

Returns True if expression1 is greater than or equal to expression2; False otherwise.

 

Syntax

Result = expression1 > = expression2

Is

Name

Compare objects

 

Description

Returns True if object1 and object2 refer to the same memory location (if they are in fact the same object).

 

Syntax

Result = object1 Is object2

 

Note

Use the Not operator (see under Logical Operators ) with the Is operator to get the opposite effect.

Result = object1 Not Is object2 Use the Nothing keyword with the Is operator to check if an object reference is valid. Returns True if object has been destroyed ( Set object = Nothing ).

Result = object Is Nothing Be careful, Nothing is not the same as Empty . Nothing references an invalid object reference, whereas Empty is used for any variable, which has been assigned the value of Empty , or has not yet been assigned a value.

Logical Operators

The logical operators are used for performing logical operations on expressions; they are listed in order of operator precedence. All logical operators can also be used as bitwise operators (see under Bitwise Operators ).

Not

Used to

Negate the expression

 

Returns

Returns the logical negation of an expression.

 

Syntax

Result = Not expression

 

Note

Result will be True if expression is False; and False if expression is True . Null will be returned if expression is Null .

And

Used to

Check if both expressions are true.

 

Returns

Returns True if both expressions evaluate to True; otherwise, False is returned.

 

Syntax

Result = expression1 And expression2

Or

Used to

Check if one or both expressions are true.

 

Returns

Returns True if one or both expressions evaluate to True; otherwise False is returned.

 

Syntax

Result = expression1 Or expression2

Xor

Used to

Check if one and only one expression is true.

 

Returns

Null will be returned if either expression is Null .

 

Syntax

Result = expression1 Xor expression2

 

Note

Returns True if only one of the expressions evaluates to True; otherwise False is returned.

Eqv

Used to

Check if both expressions evaluate to the same value.

 

Returns

Returns True if both expressions evaluate to the same value ( True or False ).

 

Syntax

Result = expression1 Eqv expression2

 

Note

Null will be returned if either expression is Null .

Imp

Used to

Perform a logical implication .

 

Returns

Returns these values: true Imp true = true false Imp true = true false Imp false = true false Imp Null = true Null Imp true = true true Imp false = false true Imp Null = Null Null Imp false = Null Null Imp Null = Null

 

Syntax

Result = expression1 Imp expression2

Bitwise Operators

Bitwise operators are used for comparing binary values bit-by-bit; they are listed in order of operator precedence. All bitwise operators can also be used as logical operators (see under Logical Operators ).

Not

Used to

Invert the bit values.

 

Returns

Returns 1 if bit is and vice versa.

 

Syntax

Result = Not expression If expression is 101 then result is 010 .

And

Used to

Check if both bits are set to 1 .

 

Returns

Returns 1 if both bits are 1; otherwise is returned.

 

Syntax

Result = expression1 And expression2 If expression1 is 101 and expression2 is 100 then result is 100 .

Or

Used to

Check if one of the bits is set to 1 .

 

Returns

Returns 1 if one or both bits are 1; otherwise is returned.

 

Syntax

Result = expression1 or expression2 If expression1 is 101 and expression2 is 100 then result is 101 .

Xor

Used to

Check if one and only one of the bits is set to 1 .

 

Returns

Returns 1 if only one of the bits is 1; otherwise is returned.

 

Syntax

Result = expression1 Xor expression2 If expression1 is 101 and expression2 is 100 then result is 001 .

Eqv

Used to

Checks if both bits evaluate to the same value.

 

Returns

Returns 1 if both the bits have the same value; otherwise is returned.

 

Syntax

Result = expression1 Eqv expression2 If expression1 is 101 and expression2 is 100 then result is 110 .

Imp

Used to

Performs a logical implication on 2 bits.

 

Returns

Returns these values: Imp 0 = 10 Imp 1 = 1 1 Imp 1 = 1 1 Imp 0 = 0

 

Syntax

Result = expression1 Imp expression2 If expression1 is 101 and expression2 is 100 then result is 110 .

Operator Precedence

When more than one operation occurs in an expression they are normally performed from left to right. However, there are several rules.

Operators from the arithmetic group are evaluated first, and then concatenation, comparison, and logical operators.

This is the complete order in which operations occur (operators in brackets have the same precedence):

  • ^, -, (*, /) , , Mod, (+, -)
  • &
  • = , <>, <, >, < = , > = , Is
  • Not, And, Or, Xor, Eqv, Imp

This order can be overridden by using parentheses. Operations in parentheses are evaluated before operations outside the parentheses, but inside the parentheses, the normal precedence rules apply.

Unsupported Operators

The following VB/VBA operator is not supported in VBScript:

  • Like

Math Functions

The following listing is in alphabetical order.

Abs

Returns the absolute value of a number, that is, its unsigned magnitude.

Syntax

Abs(number) number is any valid numeric expression.

Note

Null will be returned if number contains Null .

Example

Abs(-50) ' 50 Abs(50) ' 50

See also

Sgn

Atn

Returns the arctangent of a number as Variant subtype Double(5) .

Syntax

Atn(number) number is any valid numeric expression.

Note

This function takes the ratio of two sides of a right-angled 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 -(/2 to (/2 radians.

Example

Dim dblPi

 

' Calculate the

 

' value of Pi

 

dblPi = 4 * Atn(1)

See also

Cos , Sin , and Tan

Cos

Returns the cosine of an angle as Variant subtype Double(5) .

Syntax

Cos(number)

 

number is any valid numeric expression that expresses an angle in radians.

Note

This function takes an angle and returns the ratio of two sides of a right-angled triangle. The ratio is the length of the side adjacent to the angle divided by the length of the hypotenuse ( dblSecant ). The result is within the range -1 to 1, both inclusive.

 

Dim dblLength

 

dblLength = 10

 

' Convert 30 ° to radians

 

dblAngle = (30 * 3.14 / 180)

 

dblSecant = dblLength /

 

Cos(dblAngle)

See also

Atn , Sin , and Tan

Exp

Returns a Variant subtype Double(5) specifying e (the base of natural logarithms) raised to a power.

Syntax

Exp(number) Number is any valid numeric expression.

Note

A runtime error occurs if number is larger than 709.782712893. e is approximately 2.718282.

Sometimes this function is referred to as the antilogarithm, and complements the action of the Log function.

Example

Dim dblAngle, dblHSin

 

dblAngle = 1.3

 

dblHSin = (Exp( dblAngle) - Exp(

 

-1 * dblAngle)) / 2

 

Here the Exp function is used to return e raised to a power.

See also

Log

Fix

Returns the integer part of a number.

Syntax

Fix(number)

Note

Fix is internationally aware, which means that the return value is based on the locale settings on the machine.

Null is returned if number contains Null . The data type returned will be decided from the size of the integer part. Possible return data types in ascending order:

          Integer

          Long

          Double

          If number is negative, the first negative integer equal to or greater than number is returned.

Example

Dim vntPosValue

 

Dim vntNegValue

 

vntPosValue = Fix(5579.56)

 

vntNegValue = Fix(-5579.56)

 

vntPosValue now holds the value 5579, and vntNegValue the value - 5579.

          Fix is the equivalent of Int when dealing with nonnegative numbers. When you handle negative numbers, Fix returns the first negative integer, greater than, or equal to the number supplied.

Note

Int , Round , and the conversion functions CInt and CLng

Int

Returns the integer part of a number.

Syntax

Int(number)

 

Number is any valid numeric expression.

Note

Int is internationally aware, which means that the return value is based on the locale settings on the machine.

 

Null is returned if number contains Null . The data type returned will be decided from the size of the integer part. Possible return data types in ascending order:

 

Integer

 

Long

 

Double

 

If number is negative, the first negative integer equal to or less than number is returned.

Example

Dim vntPosValue

 

Dim vntNegValue

 

vntPosValue = Int(5579.56)

 

vntNegValue = Int(-5579.56)

 

vntPosValue now holds the value 5579, and vntNegValue the value - 5580. Int is the equivalent of Fix when dealing with nonnegative numbers. When you handle negative numbers, Int returns the first negative integer, less than, or equal to the number supplied.

See also

Fix , Round , and the conversion functions CInt and CLng

Log

Returns the natural logarithm of a number.

Syntax

Log(number)

 

number is any valid numeric expression greater than zero.

Example

Dim vntValueBase10

 

vntValueBase10 = Log(5) / Log(10)

 

This sample code calculates the base-10 logarithm of the number 5, which is 0.698970004336019.

See also

Exp

Randomize

Initializes the random number generator, by giving it a new seed-value. A seed-value is an initial value used for generating random numbers.

Syntax

Randomize[number]

Number is any valid numeric expression.

Note

You can repeat a sequence of random numbers, by calling the Rnd function with a negative number, before using the Randomize statement with a numeric argument.

Example

Const LNG_UPPER_BOUND = 20

 

Const LNG_LOWER_BOUND = 1

 

Dim intValue

 

Dim lngCounterIn

 

Dim lngCounterOut

 

For lngCounterOut = 1 To 3

 

Rnd -1

 

Randomize 3

 

For lngCounterIn = 1 To 3

 

intValue =

 

Int((LNG_ UPPER_BOUND -

 

LNG_LOWER_BOUND + 1) * _

 

Rnd + LNG_LOWER_BOUND)

 

MsgBox intValue

 

Next

 

Next

 

This sample has an inner loop that generates three random numbers and an outer loop that calls the Rnd function with a negative number, immediately before calling Randomize with an argument. This makes sure that the random numbers generated in the inner loop will be the same for every loop the outer loop performs.

See also

Rnd

Rnd

Returns a random number, less than 1 but greater than or equal to 0.

Syntax

Rnd[(number)]

 

number (Optional) is any valid numeric expression that determines how the random number is generated; if number is:

 

< -uses same number every time

 

> or missing-uses next random number in sequence

 

= 0 -uses most recently generated number.

Note

Use the Randomize statement, with no argument, to initialize the random-number generator with a seed based on the system timer, before calling Rnd .

 

The same number sequence is generated for any given initial seed, because each successive call to Rnd uses the previous number as the seed for the next number in the sequence.

 

Call Rnd with a negative argument immediately before using Randomize with a numeric argument, in order to repeat sequences of random numbers.

Example

Const LNG_UPPER_BOUND = 20

 

Const LNG_LOWER_BOUND = 1

 

Dim intValue

 

Dim lngCounter

 

For lngCounter = 1 To 10

 

intValue = Int( _

 

(LNG_UPPER_BOUND

 

- -

 

LNG_LOWER_BOUND + 1) * _

 

Rnd + LNG_LOWER_BOUND)

 

MsgBox intValue

 

Next

 

This produces 10 random integers in the range 1-20.

See also

Randomize

Round

Returns a number rounded to a specified number of decimal places as a Variant subtype Double(5) .

Syntax

Round(number, [numdecimalplaces]) number is any valid numeric expression. numdecimalplaces (Optional) indicates how many places to the right of the decimal separator should be included in the rounding.

Note

An integer is returned if numdecimalplaces is missing.

Example

Round(10.4)          ' Returns 10

 

Round(10.456)          ' Returns 10

 

Round(-10.456)          ' Returns -10

 

Round(10.4, 1)          ' Returns 10.4

 

Round(10.456, 2)          ' Returns 10.46

 

Round(-10.456, 2)          ' Returns -10.46

See also

Int and Fix

Sgn

Returns an integer indicating the sign of a number.

Syntax

Sgn(number)

 

Number is any valid numeric expression.

Note

Sgn returns the following when number is:

 

< 0 - -1

 

= 0 - 0

 

> 0 - 1

Example

Sgn(10.4)           ' Returns 1

   
 

Sgn(0)

 

' Returns 0

 

Sgn(-2)

 

' Returns -1

See also

Abs

Sin

Returns a Variant subtype Double(5) specifying the sine of an angle.

Syntax

Sin(number)

 

number is any valid numeric expression that expresses an angle in radians.

Note

This function takes an angle and returns the ratio of two sides of a right-angled triangle. The ratio is the length of the side opposite the angle ( dblCosecant ) divided by the length of the hypotenuse ( dblSecant ). The result is within the range -1 to 1, both inclusive.

Example

Dim dblAngle, dblCosecant

 

Dim dblSecant

 

dblSecant = 11.545

 

' Convert 30   to radians

 

dblAngle = (30 * 3.14 / 180)

 

dblCosecant = dblSecant *

 

Sin(dblAngle)

 

Here the Sin functioon is used to return the sine of an angle.

See also

Atn,.Cos, and Tan

Sqr

Returns the square root of a number.

Syntax

Sqr(number)

 

number is any valid numeric expression greater than or equal to zero.

Example

Sqr(16) ' Returns 4

Tan

Returns a Variant subtype Double(5) specifying the tangent of an angle.

Syntax

Tan(number)

 

number is any valid numeric expression that expresses an angle in radians.

Note

This function takes an angle and returns the ratio of two sides of a right-angled triangle. The ratio is the length of the side opposite the angle ( dblCosecant ) divided by the length of the side adjacent to the angle ( dblLength ).

 

The result is within the range -1 to 1, both inclusive.

Example

Tan(10.4) ' Returns 1.47566791425166

Tan(0) * ' Returns 0

Tan(--2) ' Returns 2.18503986326152

See also

Atn,.cos, and Tan


Date and Time Functions and Statements

There are a number of ways to display and represent dates and times. This includes date literals, which are valid date expression, enclosed in number signs ( # ). You need to be careful when using date literals because VBScript lets you use only the US date format, mm/dd/yyyy. This is true even if a different locale is being used on the machine. This might lead to problems when trying to use date literals in other formats, because in most cases the date will be accepted although converted to a different date. #10/12/2003# will be interpreted as October 12, 2003, but you might in fact want December 10, 2003, because your locale settings interpret dates as dd/mm/yyyy. Date literals accept only the forward slash (/) as the date separator.

The data range for a date is January 1, 100, to December 31, 9999, both inclusive. Internally, dates are stored as part of real numbers or to be more specific as a Variant subtype Double(5) . The digits to the left of the decimal separator represent the date and the digits to the right of the decimal separator represent the time. Negative numbers are used internally for representing dates prior to December 30, 1899.

The following is a list of functions used for converting and formatting dates and times.

Cdate

Returns an expression converted to Variant subtype Date(7) .

Syntax

CDate(date)

 

date is any valid date expression.

Note

CDate is internationally aware, which means that the return value is based on the locale settings on the machine. Dates and times will be formatted with the appropriate time and date separators, and for dates the correct order of year, month, and day are applied. Date and time literals are recognized.

Example

Dim dtmValue

 

dtmValue = CDate( # 12/10/2003#)

 

dtmValue now holds the value 10-12-03 , if your locale settings use the dash (-) as the date separator and the short date format is dd/mm/yy.

See also

IsDate

Date

Returns a Variant subtype Date(7) indicating the current system date.

Syntax

Date

Example

MsgBox Date

 

Assuming that today is February 28, 2004, the MsgBox now displays 28-02-04, if your locale settings use the dash (-) as the date separator and the short date format is dd/mm/yy.

See also

Now and Time

DateAdd

Adds or subtracts a time interval to a specified date and returns the new date.

Syntax

DateAdd(interval, number, date)

 

Interval can have these values:

 

d           Day

 

h           Hour

 

m           Month

 

n           Minute

 

q           Quarter

 

s           Second

 

w           Weekday

 

ww           Week of year

 

y           Day of year

 

yyyy           Year

 

number is a numeric expression that must be positive if you want to add or negative if you want to subtract.

 

number is rounded to the nearest whole number if it's not a Long value.

 

date must be a Variant or Date literal to which interval is added.

Note

DateAdd is internationally aware, which means that the return value is based on the locale settings on the machine. Dates and times will be formatted with the appropriate time and date separators and for dates the correct order of year, month, and day are applied. An error occurs if the date returned is less than the year 100.

Example

MsgBox DateAdd("m", 3, "1-Jan-04")

 

This will add 3 months to January 1, 2004, and the MsgBox now displays 01-04-04, if your locale settings use the dash (-) as the date separator and the short date format is dd/mm/yy.

See also

DateDiff and DatePart

DateDiff

Returns the interval between two dates.

 

DateDiff(interval, date1, date2,

 

[ firstdayofweek ], [ firstweekofyear ])

 

Interval can have these values:

 

d           Day

 

h           Hour

 

m           Month

 

n           Minute

 

q           Quarter

 

s           Second

 

w           Weekday

 

ww           Week of year

 

y           Day of yea r

 

yyyy           Year

 

date1 and date2 are date expressions.

 

firstdayofweek (Optional) specifies the first day of the week. Use one of the following constants:

 

vbUseSystemDayOfWeek (National Language Support (NLS) API setting. NLS functions help Win32-based applications support the differing language- and location-specific needs of users around the world)

 

vbSunday1 (Default)

 

vbMonday2

 

vbTuesday3

 

vbWednesday 4

 

vbThursday5

 

vbFriday6

 

vbSaturday7

 

firstweekofyear (Optional) specifies the first week of the year. Use one of the following constants:

 

vbUseSystem 0 (Use NLS API setting)

 

vbFirstJan1 1 (Default)

 

(Week in which January 1 occurs)

 

vbFirstFourDays 2 (First week in the new year with at least four4 days)

 

vbFirstFullWeek 3 (First full week of the new year)

Note

A negative number is returned if date1 is later in time than date2 .

Example

MsgBox DateDiff("yyyy", # 06-12-1972#, Now)

 

This will calculate the number of years between 06/12/1972 and now. In 2004, the MsgBox will display 32.

See also

DateAdd and DatePart

DatePart

Returns a specified part of a date.

Syntax

DatePart(interval, date, [firstdayofweek], [firstweekofyear])

 

Interval can have these values:

 

d Day

 

h Hour

 

m Month

 

n Minute

 

q Quarter

 

s Second

 

w Weekday

 

wwWeek of year

 

y Day of year

 

yyyy Year

 

date is a date expression.

 

firstdayofweek (Optional) specifies the first day of the week. Use one of the following constants:

 

vbUseSystemDayOfWeek 0 (NLS API setting)

 

vbSunday1 (Default)

 

vbMonday 2

 

vbTuesday3

 

vbWednesday4

 

vbThursday5

 

vbFriday 6

 

vbSaturday7

 

firstweekofyear (Optional) specifies the first week of the year. Use one of the following constants:

 

vbUseSystem 0 (Use NLS API setting)

 

vbFirstJan1 1 (default) (Week in which January 1 occurs) vbFirstFourDays 2

 

(First week in the new year with at least 4 days)

 

vbFirstFullWeek 3 (First full week of the new year)

Example

MsgBox DatePart("ww", Now, vbMonday, vbFirstFourDays) This will extract the week number from the current system date. On July 29, 2004, the MsgBox will display 31.

See also

DateAdd and DateDiff

DateSerial

Returns a Variant subtype Date(7) for the specified year, month, and day.

Syntax

DateSerial(year, month, day)

 

year is an expression that evaluates to a number between 0 and 9999. Values between 0 and 99, both inclusive, are interpreted as the years 1900-1999.

 

month is an expression that must evaluate to a number between 1 and 12.

 

day is an expression that must evaluate to a number between 1 and 31.

Note

If an argument is outside the acceptable range for that argument, it increments the next larger unit. Specifying 13 as the month will automatically increment year by 1 and subtract 12 from month leaving a value of 1. The same is true for negative values and a value of 0. However, instead of incrementing, the next larger unit is decremented.

 

An error occurs if any of the arguments is outside the Variant subtype Integer range, which is -32768 to +32767. The same is true if the result is later than December 31, 9999. If you specify the year as 0, and the month and day as 0 or a negative value, the function wrongly assumes that the year is 100 and decrements this value.

 

So DateSerial(0, 0, 0) returns 11/30/99.

Example

MsgBox DateSerial( 2004, 07, 29)

 

The MsgBox will display 29-07-04, if your locale settings use the dash (-) as the date separator and the short date format is dd/mm/yy.

See also

Date , DateValue , Day , Month , Now , TimeSerial , TimeValue , Weekday , and Year

DateValue

Returns a Variant subtype Date(7)

Syntax

DateValue(date) date is an expression representing a date, a time, or both, in the range January 1, 100, to December 31, 9999.

Note

Time information in date is not returned, but invalid time information will result in a runtime error. DateValue is internationally aware and uses the locale settings on the machine when recognizing the order of a date with only numbers and separators. If the year is omitted from date, it is obtained from the current system date.

Example

DateValue("06/12/2004")

 

DateValue("June 12, 2004")

 

DateValue("Jun 12, 2004")

 

DateValue("Jun 12")

 

All of these will return the same valid date of 06/12/04.

See also

Date , DateSerial , Day , Month , Now , TimeSerial , TimeValue , Weekday , and Year

Day

Returns a number between 1 and 31 representing the day of the month.

Syntax

Day(date)

 

date is any valid date expression.

Note

A runtime error occurs if date is not a valid date expression. Null will be returned if date contains Null .

Example

MsgBox Day("June 12, 2004")

 

The MsgBox will display 12.

See also

Date , Hour , Minute , Month , Now , Second , Weekday , and Year

FormatDateTime

See under String Functions

Hour

Returns an integer between 0 and 23, representing the hour of the day.

Syntax

Hour(time) time is any valid time expression.

Note

A runtime error occurs if time is not a valid time expression. Null will be returned if time contains Null .

Example

MsgBox Hour("12:05:12")

 

The MsgBox will display 12.

See also

Date , Day , Minute , Month , Now , Second , Weekday , and Year

IsDate

Returns a Variant subtype Boolean(11) indicating whether an expression can be converted to a valid date.

Syntax

IsDate(expression) expression is any expression you want to evaluate as a date or time.

Example

MsgBox IsDate(Now)           ' true

 

MsgBox IsDate(" ")           ' false

 

MsgBox IsDate(# 6/12/2004#) ' true

See also&

CDate , IsArray , IsEmpty , IsNull , IsNumeric , IsObject , and VarType

Minute

Returns a number between 0 and 59, both inclusive, indicating the minute of the hour.

Syntax

Minute(time)

 

time is any valid time expression.

Note

A runtime error occurs if time is not a valid time expression. Null will be returned if time contains Null .

Example

MsgBox Minute("12:45")

 

The MsgBox will display 45.

See also

Date , Day , Hour , Month , Now , Second , Weekday , and Year

Month

Returns a number between 1 and 12, both inclusive, indicating the month of the year.

Syntax

Month(date) date is any valid date expression.

Note

A runtime error occurs if date is not a valid date expression. Null will be returned if date contains Null .

Example

MsgBox Month(# 7/29/1999#)

 

The MsgBox will display 7.

See also

Date , Day , Hour , Minute , Now , Second , Weekday , and Year

MonthName

Returns a Variant subtype String(8) for the specified month.

Syntax

MonthName(month,[abbreviate]) month is a number between 1 and 12 for each month of the year beginning with January. abbreviate (Optional) is a Boolean value indicating if the month name should be abbreviated or spelled out (default).

Note

A runtime error occurs if month is outside the valid range (1-12). MonthName is internationally aware, which means that the returned strings are localized into the language specified as part of your locale settings.

Example

MsgBox MonthName(2) ' February

 

MsgBox MonthName(2, true) ' Feb

See also

WeekDayName

Now

Returns the system's current date and time.

Syntax

Now

Example

Dim dtmValue

 

dtmValue = Now dtmValue now holds the current system date and time.

See also

Date , Day , Hour , Month , Minute , Second , Weekday , and Year

Second

Returns a Variant subtype Date(7) indicating the number of seconds (0-59) in the specified time.

Syntax

Second(time)

 

time is any valid time expression.

Note

A runtime error occurs if time is not a valid time expression. Null will be returned if time contains Null .

Example

MsgBox Second("12:45:56")

 

The MsgBox will display 56.

See also

Date , Day , Hour , Minute , Month , Now , Weekday , and Year

Time

Returns a Variant subtype Date(7) indicating the current system time.

Syntax

Time

Example

Dim dtmValue

 

dtmValue = Time

dtmValue now holds the current system time.

See also

Date and Now

Timer

Returns a Variant subtype Single(5) indicating the number of seconds that have elapsed since midnight. This means that it is 'reset' every 24 hours.

Syntax

Timer

Example

Dim dtmStart, dtmStop

 

dtmStart = Timer

 

' Do processing here

 

dtmStop = Timer

 

' Display how many

 

' seconds the operation

 

' took

 

MsgBox dtmStop - dtmStart

TimeSerial

Returns a Variant subtype Date(7) for the specified hour, minute, and second.

Syntax

TimeSerial(hour, minute, second)

 

hour is an expression that evaluates to a number between 0 and 23.

 

minute is an expression that must evaluate to a number between 0 and 59.

 

second is an expression that must evaluate to a number between 0 and 59.

Note

If an argument is outside the acceptable range for that argument, it increments the next larger unit. Specifying 61 as minute will automatically increment hour by 1 and subtract 60 from minute leaving a value of 1. The same is true for negative values and a value of 0. However, instead of incrementing, the next larger unit is decremented.

 

An error occurs if any of the arguments is outside the Variant subtype Integer range, which is -32768 to +32767.

Example

MsgBox TimeSerial(23, 07, 29)

 

The MsgBox will display 23:07:29.

See also

Date , DateSerial , DateValue , Day , Month , Now , TimeValue , Weekday , and Year

TimeValue

Returns a Variant subtype Date(7) containing the time.

Syntax

TimeValue(time) time is an expression in the range 0:00:00 to 23:59:59.

Note

Date information in time is not returned, but invalid date information will result in a runtime error. Null is returned if time contains Null . You can use both 24- and 12-hour representations for the time argument.

Example

TimeValue("23:59")

 

TimeValue("11:59 PM")

 

Both will return the same valid time.

See also

Date , DateSerial , DateValue , Day , Month , Now , TimeSerial , We ekday , and Year

Weekday

Returns a number indicating the day of the week.

Syntax

Weekday(date, [firstdayofweek])

 

date is any valid date expression.

 

firstdayofweek (Optional) specifies the first day of the week. Use one of the following constants:

 

vbUseSystemDayOfWeek 0 (Use NLS API setting)

 

vbSunday1 (Default)

 

vbMonday2

 

vbTuesday3

 

vbWednesday 4

 

vbThursday5

 

vbFriday6

 

vbSaturday7

Note

Null is returned if date contains Null . A runtime occurs if date is invalid. Possible return values are:

 

vbSunday1

 

vbMonday2

 

vbTuesday3

 

vbWednesday 4

 

vbThursday5

 

vbFriday6

 

vbSaturday7

Example

Weekday(# July 29, 1999#)

 

Returns 5 for Thursday.

See also

Date , Day , Month , Now , and Year

WeekdayName

Returns a Variant subtype String(8) for the specified weekday.

Syntax

WeekdayName(weekday, [abbreviate], [firstdayofweek])

 

weekday is a number between 1 and 7 for each day of the week. This value depends on the firstdayofweek setting.

 

abbreviate (Optional) is a Boolean value indicating if the weekday name should be abbreviated or spelled out (default)

 

firstdayofweek (Optional) is a numeric value indicating the first day of the week. Use one of the following constants:

 

vbUseSystemDayOfWeek 0 (Use NLS API setting)

 

vbSunday 1 (Default)

 

vbMonday 2

 

vbTuesday 3

 

vbWednesday 4

 

vbThursday 5

 

vbFriday 6

 

vbSaturday 7

Note

A runtime error occurs if weekday is outside the valid range (1-7). WeekdayName is internationally aware, which means that the returned strings are localized into the language specified as part of your locale settings.

Example

WeekdayName(2, , vbSunday) ' Monday

 

WeekdayName(1, , vbMonday) ' Monday

See also

MonthName

Year

Returns a number indicating the year.

Syntax

Year(date)

 

date is any valid date expression.

Note

A runtime error occurs if date is not a valid date expression. Null will be returned if date contains Null .

Example

MsgBox Year(# 6/12/2004#)

 

The MsgBox will display 2004.

See also

Date , Day , Month , Now , and Weekday


Unsupported Date Functions and Statements

The following VB/VBA statements are not supported in VBScript.

Function/Statement Name Alternatives

Date statement

Sets the system date, which is not possible in VBScript.

Time statement

Sets the system time, which is not possible in VBScript.

Array Functions and Statements

One major difference between VB/VBA and VBScript is the way you can declare your arrays. VBScript does not support the Option Base statement and you cannot declare arrays that are not zero-based .

The following is a list of functions and statements that you can use for array manipulation in VBScript.

Array

Returns a comma-delimited list of values as a Variant subtype Array (8192) .

Syntax

Array(arglist)

 

arglist is a comma-delimited list of values that is inserted into the one-dimensional array in the order they appear in the list.

Note

An array of zero length is created if arglist contains no arguments.

 

All arrays in VBScript are zero-based, which means that the first element in the list will be element 0 in the returned array.

Example

Dim arrstrTest

 

' Create an array with three

 

elements

 

arrstrTest = Array( _

 

125pt "Bart", "Lisa",

 

"Maggie")

 

' Show the first list element

 

' now in the array

 

MsgBox arrstrTest(0)

 

MsgBox displays Bart.

See also

Dim

Erase

Reinitializes the elements if it is a fixed- size array and deallocates the memory used if it is a dynamic array.

Syntax

Erase array

 

array is the array to be reinitialized or erased.

Note

You must know if you are using a fixed-size or a dynamic array, because this statement behaves differently depending on the array type.

 

Because the memory is deallocated when using Erase with dynamic arrays, you must redeclare the array structure with the ReDim statement, before you use it again.

Fixed-size arrays are reinitialized differently depending on the contents of the elements

 

Numeric Set to

 

Strings Set to ' '

 

Objects Set to Nothing

Example

Dim arrstrDynamic()

 

Dim arrstrFixed(3)

 

' Allocate space for the

 

' dynamic array

 

ReDim arrstrDynamic(3)

 

' Free the memory used by

 

' the dynamic array

 

Erase arrstrDynamic

 

' Reinitialize the elements

 

' in the fixed-size array

 

Erase arrstrFixed

See also

Dim and ReDim

For Each

Performs a group of statements repeatedly for each element in a collection or an array.

Syntax

For Each element In group

 

[statements]

 

[Exit For]

 

Next [element]

 

element is a variable used for iterating through the elements in a collection or an array.

 

group is the name of the object or array.

 

statements is one or more statements you want to execute on each item in the group.

Note

The For Each loop is only entered if there is at least one element in the collection or array. All the statements in the loop are executed for all the elements in the group. You can control this by executing the Exit For statement if a certain condition is met. This will exit the loop and start executing on the first line after the Next statement.

 

The For Each loops can be nested, but you must make sure that each loop element is unique.

Example

Dim arrstrLoop

 

Dim strElement

 

' Create the array

 

arrstrLoop = Array _

 

( "Bart", "Lisa", "Maggie")

 

' Loop through the array

 

For Each strElement In _

 

arrstrLoop

 

' Display element content

 

MsgBox strElement

 

Next

IsArray

Returns a Variant subtype Boolean(11) indicating if a variable is an array.

Syntax

IsArray(varname)

 

varname is a variable you want to check is an array.

Note

Only returns True if varname is an array.

Example

Dim strName

 

Dim arrstrFixed(3)

 

strName = "Wrox is Great!"

 

MsgBox IsArray( strName)

 

' false

 

MsgBox IsArray( arrstrFixed)

 

' true

See also

IsDate , IsEmpty , IsNull , IsNumeric , IsObject , and VarType

Lbound

Returns the smallest possible subscript for the dimension indicated.

Syntax

LBound(arrayname[,dimension])

 

arrayname is the name of the array variable. dimension is an integer indicating the dimension you want to know the smallest possible subscript for. The dimension starts with 1, which is also the default that will be used if this argument is omitted.

Note

The smallest possible subscript for any array is always 0 in VBScript. LBound will raise a runtime error if the array has not been initialized .

Example

Dim arrstrFixed(3)

 

MsgBox LBound(arrstrFixed)

 

MsgBox displays 0.

See also

Dim , ReDim , and UBound

ReDim

This statement is used to size or resize a dynamic array.

Syntax

ReDim [Preserve] varname(subscripts[, varname(subscripts)]...)

 

Preserve (Optional) is used to preserve the data in an existing array, when you resize it. The overhead of using this functionality is quite high and should only be used when necessary.

 

varname is the name of the array variable. subscripts is the dimension of the array variable varname . You can declare up to 60 multiple dimensions. The syntax is: upper[, upper]... where you indicate the upper bounds of the subscript . The lower bound is always 0.

Note

A dynamic array must already have been declared without dimension subscripts, when you size or resize it. If you use the Preserve keyword, only the last array dimension can be resized and the number of dimensions will remain unchanged.

Since an array can be made smaller when resizing, you should take care that you don't lose any data already in the array.

Example

Dim arrstrDynamic()

 

' Size the dimension to

 

' contain one dimension

 

' with 3 elements

 

ReDim arrstrDynamic(2)

 

' Put data in the array

 

arrstrDynamic(0) = "1"

 

arrstrDynamic(1) = "2"

 

arrstrDynamic(2) = "3"

 

' Resize the array, but

 

' keep the existing data

 

ReDim Preserve arrstrDynamic(5)

 

' Display the 3rd element

 

MsgBox arrstrDynamic(2)

 

MsgBox displays 3.

See also

Dim and Set

Ubound

Returns the largest possible subscript for the dimension indicated.

Syntax

UBound(arrayname[, dimension])

 

arrayname is the name of the array variable. dimension is an integer indicating the dimension you want to know the largest possible subscript for. The dimension starts with 1, which is also the default that will be used if this argument is omitted.

Note

UBound will raise a runtime error if the array has not been initialized.

 

If the array is empty, -1 is returned.

Example

Dim arrstrFixed(3)

 

MsgBox UBound(arrstrFixed)

 

MsgBox displays 3.

See also

Dim , Ubound , and ReDim


Unsupported Array Functions and Statements

The following VB/VBA constructs are not supported in VBScript:

  • Option Base

String Functions and Statements

FormatCurrency

Formats an expression as a currency value with the current currency symbol. The currency symbol is defined in Regional Settings in Windows Control Panel

Syntax

FormatCurrency(expression [,numdigitsafterdecimal [,includeleadingdigit [,useparensfornegativenumbers [,groupdigits]]]])

 

expression is the expression that you want formatted.

 

numdigitsafterdecimal (Optional) is a numeric value that indicates how many places to the right of the decimal separator should be displayed. If you omit this argument, the default value (-1) will be assumed and the settings from Control Panel will be used.

 

includeleadingdigit (Optional) indicates if a leading zero is displayed for fractional values. Use one of the following constants:

 

vbUseDefault 2 (Uses the settings from the Number tab in Control Panel )

 

vbtrue -1

 

vbfalse 0

useparensfornegativenumbers (Optional) indicates if negative numbers are enclosed in parentheses. Use one of the following constants:

 

vbUseDefault 2 (Uses the settings from the Regional Settings tab in Control Panel )

 

vbTrue -1

 

vbFalse 0

 

groupdigits (Optional) indicates if numbers are grouped using the thousand separator specified in Control Panel . Use one of the following constants:

 

vbUseDefault 2 (Uses the settings from the Regional Settings tab in Control Panel )

 

vbtrue -1

 

vbfalse 0

Note

The way the currency symbol is placed in relation to the currency value is determined by the settings in the Regional Settings tab in Control Panel -Is the currency symbol placed before the number or after the number, is there a space between the symbol and the number, and so on.

Example

MsgBox FormatCurrency(7500000)

 

MsgBox FormatCurrency(7500000, , vbtrue)

 

MsgBox FormatCurrency(7500000, 2, vbtrue)

 

If the currency symbol is a dollar sign ($), the thousand separator a comma (,), and the currency symbol placed in front of the number with no spaces between, then MsgBox will display $7,500,000.00 in all these statements.

See also

FormatDateTime , FormatNumber , and FormatPercent

FormatDateTime

Returns a string formatted as a date and/or time.

Syntax

FormatDateTime(date , [namedformat])

 

date is any valid date expression. namedformat (Optional) is a numeric value that indicates the date/time format used. Use one of the following constants:

 

vbGeneralDate (Format date (if present) and time (if present) using the short date and long time format from the machine's locale settings)

 

vbLongDate 1 (Format date using the long date format from the machine's locale settings)

 

vbShortDate 2 (Format date using the short date format from the machine's locale settings)

 

vbLongTime 3 (Format time using the long time format from the machine's locale settings)

 

vbShortTime 4 (Format time using the short time format from the machine's locale settings)

Note

A runtime error occurs if date is not a valid date expression. Null will be returned if date contains Null .

Example

MsgBox FormatDateTime(Now, vbShortDate)

 

On June 12, 2004, the MsgBox will display 06/12/04, if the locale settings use mm/dd/yy as the short date order and the forward slash (/) as the date separator.

See also

FormatCurrency , FormatNumber , and FormatPercent

FormatNumber

Returns a string formatted as a number.

Syntax

FormatNumber (expression ,

 

[ , numdigitsafterdecimal

 

[ , includeleadingdigit

 

[ , useparensfornegativenumbers [ , groupDigits]]]])

 

expression is the expression that you want formatted.

 

numdigitsafterdecimal (Optional) is a numeric value that indicates how many places to the right of the decimal separator should be displayed. If you omit this argument, the default value (-1) will be assumed and the settings from Control Panel will be used.

 

includeleadingdigit (Optional) indicates if a leading zero is displayed for fractional values. Use one of the following constants:

 

TristateUseDefault -2 (Uses the settings from the Number tab in Control Panel )

 

TristateTrue -1

 

TristateFalse

 

useparensfornegativenumbers (Optional) indicates if negative numbers are enclosed in parentheses. Use one of the following constants:

 

TristateUseDefault -2 (Uses the settings from the Number tab in Control Panel )

 

TristateTrue -1

 

TristateFalse 0

 

groupdigits (Optional) indicates if numbers are grouped using the thousand separator specified in Control Panel . Use one of the following constants:

 

TristateUseDefault -2 (Uses the settings from the Number tab in Control Panel )

 

TristateTrue -1

 

TristateFalse 0

Note

The Number tab in Regional Settings in Control Panel supplies all the information used for formatting.

Example

MsgBox FormatNumber("50000", 2,

 

vbtrue, vbfalse, vbtrue)

 

MsgBox FormatNumber("50000")

 

The MsgBox will display 50,000.00, if the locale settings use a comma (,) as the thousand separator and a period (.) as the decimal separator.

See also

FormatCurrency , FormatDateTime , and FormatPercent

FormatPercent

Returns a string formatted as a percentage, such as 45%.

Syntax

FormatPercent(expression,

 

[ , numdigitsafterdecimal

 

[ , includeleadingdigit

 

[ , useparensfornegativenumbers [ , groupDigits]]]])

 

expression is any valid expression that you want formatted.

 

numdigitsafterdecimal (Optional) is a numeric value that indicates how many places to the right of the decimal separator should be displayed. If you omit this argument, the default value (-1) will be assumed and the settings from Control Panel will be used.

 

includeleadingdigit (Optional) indicates if a leading zero is displayed for fractional values. Use one of the following constants:

 

TristateUseDefault -2 (Uses the settings from the Number tab in Control Panel )

 

TristateTrue -1

 

TristateFalse 0

 

useparensfornegativenumbers (Optional) indicates if negative numbers are enclosed in parentheses. Use one of the following constants:

 

TristateUseDefault -2 (Uses the settings from the Number tab in

 

Control Panel )

 

TristateTrue -1

 

TristateFalse 0

 

groupdigits (Optional) indicates if numbers are grouped using the thousand separator specified in Control Panel . Use one of the following constants:

 

TristateUseDefault -2 (Uses the settings from the Number tab in Control Panel )

 

TristateTrue -1

 

TristateFalse 0

Note

The Number tab in Regional Settings in Control Panel supplies all the information used for formatting.

Example

MsgBox FormatPercent(4 / 45)

 

MsgBox FormatPercent(4 / 45, 2,

 

vbtrue, vbtrue, vbtrue)

 

The MsgBox will display 8.89%, if the locale settings use a period (.) as the decimal separator.

See also

FormatCurrency , FormatDateTime , and FormatNumber

InStr

Returns an integer indicating the position for the first occurrence of a substring within a string.

Syntax

InStr([start,] string1, string2[, compare])

 

start (Optional) is any valid nonnegative expression indicating the starting position for the search within string1 . Noninteger values are rounded. This argument is required if the compare argument is specified.

 

string1 is the string you want to search within.

 

string2 is the substring you want to search for.

 

compare (Optional) indicates the comparison method used when evaluating. Use one of the following constants:

 

vbBinaryCompare (Default) (Performs a binary comparison, that is, a case-sensitive comparison)

 

vbTextCompare 1 (Performs a textual comparison, that is, a non-case-sensitive comparison)

Note

A runtime error will occur, if start contains Null . If start is larger than the length of string2 ( > Len(string2)) 0 will be returned.

 

Possible return values for different stringx settings:

 

string1           Zero-length          

 

string1          Null           Null

 

string2          Zero-length           start

 

string2          Null           Null

 

string2          Not found          

 

string2           Found           Position

Example

Dim lngStartPos

 

Dim lngFoundPos

 

Dim strSearchWithin

 

Dim strSearchFor

 

' Set the start pos

 

lngStartPos = 1

 

' Initialize the strings

 

strSearchWithin = _

 

"This is a test string"

 

strSearchFor = "t"

 

' Find the first occurrence

 

lngFoundPos = InStr( _

 

lngStartPos, _

 

strSearchWithin, _

 

strSearchFor)

 

' Loop through the string

 

Do While lngFoundPos >

 

' Display the found position

 

MsgBox lngFoundPos

 

' Set the new start pos to

 

' the char after the found

 

' position

 

lngStartPos = lngFoundPos + 1

 

' Find the next occurrence

 

lngFoundPos = InStr( _

 

lngStartPos, _

 

strSearchWithin, _

 

strSearchFor)

 

Loop

 

This code finds all occurrences of the letter t in string1 , at position 11, 14, and 17. Please note that we use binary comparison here, which means that the uppercase T will not be 'found.' If you want to perform a case-insensitive search, you will need to specify the compare argument as vbTextCompare .

See also

InStrB and InStrRev

InStrB

Returns an integer indicating the byte position for the first occurrence of a substring within a string containing byte data.

Syntax

InStrB([start,] string1, string2[, compare])

 

start (Optional) is any valid nonnegative expression indicating the starting position for the search within string1 . Noninteger values are rounded. This argument is required, if the compare argument is specified.

 

string1 is the string containing byte data you want to search within.

 

string2 is the substring you want to search for. compare (Optional) indicates the comparison method used when evaluating. Use one of the following constants:

 

vbBinaryCompare -0 (Default) (Performs a binary comparison, that is, a case-sensitive comparison)

 

vbTextCompare -1 (Performs a textual comparison, that is, a non-case-sensitive comparison)

Note

A runtime error will occur, if start contains Null . If start is larger than the length of string2 ( > Len(string2)) , 0 will be returned.

 

Possible return values for different stringx settings:

 

string1           Zero-length          

 

string1          Null           Null

 

string2           Zero-length           start

 

string2          Null           Null

 

string2           Not found          

 

string2           Found           Position

Example

Dim lngStartPos

 

Dim lngFoundPos

 

Dim strSearchWithin

 

Dim strSearchFor

 

' Set the start pos

 

lngStartPos = 1

 

' Initialize the strings

 

strSearchWithin = _

 

"This is a test string"

 

strSearchFor = ChrB(0)

 

' Find the first occurrence

 

lngFoundPos = InStrB( _

 

lngStartPos, _

 

strSearchWithin, _

 

strSearchFor)

 

' Loop through the string

 

Do While lngFoundPos >

 

' Display the found position

 

MsgBox lngFoundPos

 

' Set the new start pos to

 

' the char after the

 

' found position

 

lngStartPos = lngFoundPos + 1

 

' Find the next occurrence

 

lngFoundPos = InStrB( _

 

lngStartPos, _

 

strSearchWithin, _

 

strSearchFor)

 

Loop

 

This code finds all occurrences of the byte value 0 in string1 , at position 2, 4, 6, , 40, and 42. This is because only the first byte of the Unicode character is used for the character. If you use a double-byte character set like the Japanese, the second byte will also contain a nonzero value.

See also

InStr and InStrRev

InStrRev

Returns an integer indicating the position of the first occurrence of a substring within a string starting from the end of the string. This is the reverse functionality of InStr .

Syntax

InStrRev(string1, string2[, start[, compare]])

 

string1 is the string you want to search within.

 

string2 is the substring you want to search for.

 

start (Optional) is any valid nonnegative expression indicating the starting position for the search within string1; - 1 is the default and it will be used if this argument is omitted.

 

compare (Optional) indicates the comparison method used when evaluating. Use one of the following constants:

 

vbBinaryCompare -0 (Default) (Performs a binary comparison, that is, a case-sensitive comparison)

 

vbTextCompare -1 (Performs a textual comparison, that is, a non-case-sensitive comparison)

Note

A runtime error will occur, if start contains Null .

 

If start is larger than the length of string2 ( > Len(string2)) , will be returned.

 

Possible return values for different stringx settings:

 

string1           Zero-length          

   
 

string1           Null           Null

   
 

string2           Zero-length           start

 

string2           Null           Null

 

string2           Not found          

 

string2 Found           Position

 

InStrRev and InStr do not share the same syntax.

Example

Dim lngStartPos

 

Dim lngFoundPos

 

Dim strSearchWithin

 

Dim strSearchFor

 

' Set the start pos

 

lngStartPos = -1

 

' Initialize the strings

 

strSearchWithin = _

 

"This is a test string"

 

strSearchFor = "t"

 

' Find the first occurrence

 

lngFoundPos = InStrB( _

 

lngStartPos, _

 

47.8pt strSearchWithin, _

 

47.8pt strSearchFor, lngStartPos)

 

' Loop through the string

 

Do While lngFoundPos >

 

' Display the found

 

' position

 

MsgBox lngFoundPos

 

' Set the new start pos to

 

' the char before the

 

' found position

 

lngStartPos = lngFoundPos -1

 

' Find the next occurrence

 

lngFoundPos = InStrB( _

 

strSearchWithin, _

 

strSearchFor, _

 

lngStartPos)

 

Loop

 

This code finds all occurrences of the letter t in string1 , at position 17, 14, and 11. Please note that we use binary comparison here, which means that the uppercase T will not be 'found.' If you want to perform a case-insensitive search, you will need to specify the compare argument as vbTextCompare .

See also

InStr and InStrB

Join

Joins a number of substrings in an array to form the returned string.

Syntax

Join(list[, delimiter ])

 

list is a one-dimensional array that contains all the substrings that you want to join.

 

delimiter (Optional) is the character(s) used to separate the substrings. A space character ' ' is used as the delimiter if this argument is omitted.

Note

All the substrings are concatenated with no delimiter if a zero-length string is used as delimiter. If any element in the array is empty, a zero-length string will be used as the value.

Example

Dim strLights

 

Dim arrstrColors(3)

 

˜ Fill the array

 

arrstrColors(0) = 'Red'

 

arrstrColors(1) = "Yellow"

 

arrstrColors(2) = "Green"

 

' Join the array into a string

 

strLights = Join( arrstrColors, ",")

 

strLights contains "Red,Yellow,Green" .

See also

Split

Lcase

Converts all alpha characters in a string to lowercase.

Syntax

LCase(string)

 

string is the string you want converted to lowercase.

Note

Null is returned if string contains Null . Only uppercase letters are converted.

Example

MsgBox LCase("ThisIsLowerCase")

 

MsgBox displays thisislowercase.

See also

Ucase

Left

Returns length number of leftmost characters from string.

Syntax

Left(string, length)

 

string is the string you want to extract a number of characters from.

 

length is the number of characters you want to extract starting from the left. The entire string will be returned if length is equal to or greater than the total number of characters in string.

Note

Null is returned if string contains Null .

Example

Dim strExtract

 

strExtract = "LeftRight"

 

MsgBox Left(strExtract, 4)

 

MsgBox displays Left.

See also

Len , LenB , Mid , MidB , and Right

Len

Returns the number of characters in a string.

Syntax

Len(string)

 

string is any valid string expression you want the length of.

Note

Null is returned if string contains Null .

Example

Dim strLength

 

strLength = "1 2 3 4 5 6 7 8 9"

 

MsgBox Len(strLength)

 

MsgBox displays 17.

See also

Left , LenB , Mid , MidB , and Right

LenB

Returns the number of bytes used to represent a string.

Syntax

LenB(string)

 

string is any valid string expression you want the number of bytes for.

Note

Null is returned if string contains Null .

Example

Dim strLength

 

strLength = "123456789"

 

MsgBox LenB(strLength)

 

MsgBox displays 18.

See also

Left , Len , Mid , MidB , and Right

Ltrim

Trims a string of leading spaces; ' ' or Chr(32) .

Syntax

LTrim(string)

 

string is any valid string expression you want to trim leading (leftmost) spaces from.

Note

Null is returned if string contains Null .

Example

Dim strSpaces

 

strSpaces = " Hello again *"

 

MsgBox LTrim(strSpaces)

 

MsgBox displays Hello again *.

See also

Left , Mid , Right , Rtrim , and Trim

Mid

Returns a specified number of characters from any position in a string.

Syntax

Mid(string, start[, length])

 

string is any valid string expression you want to extract characters from.

 

start is the starting position for extracting the characters. A zero-length string is returned if it is greater than the number of characters in string.

 

length (Optional) is the number of characters you want to extract. All characters from start to the end of the string are returned if this argument is omitted or if length is greater than the number of characters counting from start.

Note

Null is returned if string contains Null .

Example

Dim strExtract

 

strExtract = "Find ME in here"

 

MsgBox Mid(strExtract, 6, 2)

 

MsgBox displays ME.

See also

Left , Len , LenB , LTrim , MidB , Right , Rtrim , and Trim

MidB

Returns a specified number of bytes from any position in a string containing byte data.

Syntax

MidB(string, start[, length])

 

string is a string expression containing byte data you want to extract characters from.

 

start is the starting position for extracting the bytes. A

 

zero-length string is returned if it is greater than the number of bytes in string.

 

length (Optional) is the number of bytes you want to extract. All bytes from start to the

 

end of the string are returned if this argument is omitted or if length is greater than

 

the number of bytes counting from start.

Note

Null is returned if string contains Null .

Example

Dim strExtract

 

strExtract = "Find ME in here"

 

MsgBox MidB(strExtract, 11, 4)

 

MsgBox displays ME because VBScript uses 2 bytes to represent a character. The first byte contains the ANSI character code when dealing with 'normal' ANSI characters like M, and the next byte is 0. So byte 11 in the string is the first byte for the letter M and then we extract 4 bytes/2 characters.

See also

Left , Len , LTrim , Mid , Right , Rtrim , and Trim

Replace

Replaces a substring within a string with another substring a specified number of times.

Syntax

Replace(expression , find , replacewith[ , start[ , count[ , compare]]])

 

expression is a string expression that contains the substring you want to replace.

 

find is the substring you want to replace.

 

replacewith is the substring you want to replace with.

 

start (Optional) is the starting position within expression for replacing the substring. 1 (default), the first position, will be used if this argument is omitted. You must also specify the count argument if you want to use start.

 

count (Optional) is the number of times you want to replace find . -1 (default) will be used if this argument is omitted, which means all find in the expression. You must also specify the start argument if you want to use count .

 

compare (Optional) indicates the comparison method used when evaluating. Use one of the following constants:

 

vbBinaryCompare -0 (Default) (Performs a binary comparison, that is, a case-sensitive comparison)

 

vbTextCompare -1 (Performs a textual comparison, that is, a non-case-sensitive comparison)

Note

If start and count are specified, the return value will be the original expression, with find replaced count times with replacewith , from start to the end of the expression, and not the complete string. A zero-length string is returned if start is greater than the length of expression (start > Len(expression)) . All occurrences of find will be removed if replacewith is a zero-length string ('').

 

Possible return values for different argument settings:

 

expression           Zero-length           zero-length

 

expression           Null           Error

 

find           Zero-length           expression

 

count          0           expression

Example

Dim strReplace

 

strReplace = Replace( _

 

"****I use binary", _

 

"I", "You", 5, 1, _

 

vbBinaryCompare)

 

' You use binary

 

strReplace = Replace( _

 

"****I use text", "i", _

 

"You", , , _

 

vbTextCompare)

 

' ****You use text

See also

Left , Len , LTrim , Mid , Right , Rtrim , and Trim

Right

Returns length number of rightmost characters from string.

Syntax

Right(string , length)

 

string is the string you want to extract a number of characters from.

 

length is the number of characters you want to extract starting from the right. The entire string will be returned if length is equal to or greater than the total number of characters in string.

Note

Null is returned if string contains Null .

Example

Dim strExtract

 

strExtract = "LeftRight"

 

MsgBox Right(strExtract, 5)

 

MsgBox displays Right.

See also

Left , Len , LenB , Mid , and MidB

RTrim

Trims a string of trailing spaces; ' ' or Chr(32) .

Syntax

RTrim(string)

 

string is any valid string expression you want to trim trailing (rightmost) spaces from.

Note

-

Example

Dim strSpaces

 

strSpaces = "* Hello again "

 

MsgBox RTrim(strSpaces)

 

MsgBox displays * Hello again.

See also

Left , LTrim , Mid , Right , and Trim

Space

Returns a string made up of a specified number of spaces (' ').

Syntax

Space(number)

 

number is the number of spaces you want returned.

Example

Dim strSpaces

 

strSpaces = "Hello again"

 

MsgBox "*" & Space(5) & strSpaces

 

MsgBox displays ^* Hello again.

See also

String

Split

Returns a zero-based one-dimensional array 'extracted' from the supplied string expression.

Syntax

Split(expression[ , delimiter[ , count[ , compare]]]))

 

expression is the string containing substrings and delimiters that you want to split up and put into a zero-based one-dimensional array.

 

delimiter (Optional) is the character that separates the substrings. A space character will be used if this argument is omitted.

 

count (Optional) indicates the number of substrings to return. -1 (default) means all substrings will be returned.

 

compare (Optional) indicates the comparison method used when evaluating. Use one of the following constants:

 

vbBinaryCompare -0 (Default) (Performs a binary comparison, that is, a case-sensitive comparison)

 

vbTextCompare -1 (Performs a textual comparison, that is, a non-case-sensitive comparison)

Note

An empty array will be returned if expression is a zero-length string. The result of the Split function cannot be assigned to a variable of Variant subtype Array (8192) . A runtime error occurs if you try to do so.

Example

Dim arrstrSplit

 

Dim strSplit

 

' Initialize the string

 

strSplit = _

 

"1,2,3,4,5,6,7,8,9,0"

 

' Split the string using _

 

' comma as the delimiter

 

arrstrSplit = Split( _

 

strSplit, ",")

 

The array arrstrSplit now holds 10 elements, 1,2, , 0.

See also

Join

StrComp

Performs a string comparison and returns the result.

Syntax

StrComp(string1 , string2[ , compare])

 

string1 is a valid string expression.

 

string2 is a valid string expression.

 

compare (Optional) indicates the comparison method used when evaluating. Use one of the following constants:

 

vbBinaryCompare -0 (Default) (Performs a binary comparison, that is, a case-sensitive comparison)

 

vbTextCompare -1 (Performs a textual comparison, that is, a non-case-sensitive comparison)

Note

Possible return values for different stringx settings

 

string1 < string2          -1

 

string1 = string2          0

 

string1 > string2          1

 

Null is returned if string1 or string2 is Null .

Example

Dim intResult

 

intResult = StrComp( _

 

"abc", "ABC", _

 

vbTextCompare)

 

' 0

 

intResult = StrComp( _

 

"ABC", "abc", _

 

vbBinaryCompare)

 

' -1

 

intResult = StrComp( _

 

"abc", "ABC")

 

' 1

See also

String

String

Returns a string with a substring repeated a specified number of times.

Syntax

String(number , character)

 

number indicates the length of the returned string.

 

character is the character code or string expression for the character used to build the returned string. Only the first character of a string expression is used.

Note

Null is returned if number or character contains Null . The character code will automatically be converted to a valid character code if it is greater than 255. The formula is character Mod 256.

Example

Dim strChars

 

strChars = "Hello again"

 

MsgBox "*") & Space(5) & Starspace _

 

MsgBox displays *Hello again.

See also

String

StrReverse

Returns a string with the character order reversed .

Syntax

StrReverse(string)

 

string is the string expression you want reversed.

Note

A runtime error occurs if string is Null . If string is a zero-length string, a zero-length string will be returned.

 

The case of the characters is not changed.

Example

MsgBox StrReverse("Hello again")

 

MsgBox displays niaga olleH.

Trim

This trims a string of leading and trailing spaces; ' ' or Chr(32) .

Syntax

Trim(string)

 

string is any valid string expression you want to trim leading (leftmost) and trailing (rightmost) spaces from.

Note

Null is returned if string contains Null .

Example

Dim strSpaces

 

strSpaces = " *Hello again* "

 

MsgBox Trim(strSpaces)

 

MsgBox displays *Hello again*.

See also

Left , Ltrim , Mid , Right , and RTrim

UCase

Converts all alpha characters in a string to uppercase and returns the result.

Syntax

UCase(string)

 

string is the string you want converted to uppercase.

Note

Null is returned if string contains Null . Only lowercase letters are converted.

Example

MsgBox UCase("ThisIsUpperCase")

 

MsgBox displays THISISUPPERCASE.

See also

Lcase


Unsupported String Functions, Statements, and Constructs

The following VB/VBA string functions/statements and constructs are not supported in VBScript.

Function/Statement Name Alternative

Format

FormatCurrency , FormatDateTime , FormatNumber , and FormatPercent

Mid (statement)

Left , Mid , and InStr functions, or the Replace function.

 

Here is how to replace a substring identified by characters using the Replace function.

 

Dim strText

 

Dim strFind

 

Dim strSubstitute

 

strText = "This is the text I want

 

to replace a substring in"

 

strFind = "want to replace"

 

strSubstitute = "have replaced "

 

strText = Replace(strText, _

 

strFind, strSubstitute)

 

strText now holds "This is the text I have replaced a substring in" .

 

Here is how to replace a substring identified by position and length using the InStr , Left , and Mid functions.

 

Dim strText

 

Dim strSubstitute

 

strText = "This is the text + _

 

I want to replace a + _

 

substring in"

 

strSubstitute = "have replaced"

 

strText = Left (strText, 19) &

 

strSubstitute & Mid$(strText, \_

 

35, Len(strText) - 34)

 

strText now holds "This is the text I have replaced a substring in" .

StrConv

It is very unlikely that this will be needed as all variables are Variant and this will be done implicitly.

Fixed length strings (Dim strMessage As String * 50) are not supported.


String Constants

Constant Value Description

vbCr

Chr(13)

Carriage Return.

vbCrLf

Chr(13) & Chr(10)

A combination of Carriage Return and line feed.

vbFormFeed

Chr(12)

Form Feed*

vbLf

Chr(10)

Line Feed

vbNewLine

Chr(13) & Chr(10) or Chr(10)

New line character. This is platform-specific, meaning whatever is appropriate for the current platform

vbNullChar

Chr(0)

Character with the value of 0

vbNullString

String with the value of 0

This is not the same as a zero-length string (''). Mainly used for calling external procedures

vbTab

Chr(9)

Tab (horizontal)

VbVerticalTab

Chr(11)

Tab (vertical)*

*Not useful in Microsoft Windows.


Conversion Functions

Asc

Returns the ANSI character code for the first character in a string.

Syntax

Asc(string)

string is any valid string expression.

Note

A runtime error occurs if string doesn't contain any characters . string is converted to a String subtype if it's a numeric subtype.

Example

intCharCode = Asc("WROX")

intCharCode now holds the value 87, which is the ANSI character code for 'W.'

See also

AscB , AscW , Chr , ChrB , and ChrW

AscB

Returns the ANSI character code for the first byte in a string containing byte data.

Syntax

AscB(string)

string is any valid string expression.

Note

A runtime error occurs if string doesn't contain any characters. For normal ANSI strings this function will return the same as the Asc function. Only if the string is in Unicode format will it be different from Asc . Unicode characters are represented by 2 bytes as opposed to ANSI characters that only need 1.

Example

intCharCode = AscB("WROX")

intCharCode now holds the value 87, which is the ANSI character code for 'W.'

See also

Asc , AscW , Chr , ChrB , and ChrW

AscW

Returns the Unicode character code for the first character in a string.

Syntax

AscW(string)

string is any valid string expression.

Note

A runtime error occurs if string doesn't contain any characters. string is converted to a String subtype if it's a numeric subtype. For use on 32-bit Unicode enabled platforms only, to avoid conversion from Unicode to ANSI.

Example

intCharCode = AscW("WROX")

intCharCode now holds the value 87, which is the Unicode character code for 'W.'

See also

Asc , AscB , Chr , ChrB , and ChrW

Cbool

Returns a Boolean value ( Variant Subtype 11 ) corresponding to the value of an expression.

Syntax

CBool(expression)

expression is any valid expression.

Note

A runtime error occurs if expression can't be evaluated to a numeric value.

If expression evaluates to zero then False is returned; otherwise , True is returned.

Example

Dim intCounter, blnValue

intCounter = 5

blnValue = CBool(intCounter)

blnValue now holds the value True, because intCounter holds a nonzero value.

See also

CByte , CCur , CDbl , CInt , CLng , CSng , and CStr

Cbyte

Returns an expression converted to Variant subtype Byte(17) .

Syntax

CByte(expression) expression is any valid numeric expression.

Note

A runtime error occurs if expression can't be evaluated to a numeric value or if expression evaluates to a value outside the acceptable range for a byte (0-255). Fractional values are rounded.

Example

Dim dblValue, bytValue

dblValue = 5.456

bytValue = CByte(dblValue)

bytValue now holds the value 5, because dblValue is rounded.

See also

CBool , CCur , CDbl , CInt , CLng , CSng , and CStr

Ccur

Returns an expression converted to Variant subtype Currency (6) .

Syntax

CCur(expression) expression is any valid expression.

Note

CCur is internationally aware, which means that the return value is based on the locale settings on the machine. Numbers will be formatted with the appropriate decimal separator and the fourth digit to the right of the separator is rounded up if the fifth digit is 5 or higher.

Example

Dim dblValue, curValue

dblValue = 724.555789

curValue = CCur(dblValue)

curValue now holds the value 724.5558 or 724,5558, depending on the separator.

See also

CBool , CByte , CDbl , CInt , CLng , CSng , and CStr

Cdate

See under Date and Time Functions and Statements

CDbl

Returns an expression converted to Variant subtype Double (5) .

Syntax

CDbl(expression)

expression is any valid expression.

Note

CDbl is internationally aware, which means that the return value is based on the locale settings on the machine. Numbers will be formatted with the appropriate decimal separator. A runtime error occurs if expression lies outside the range (-1.79769313486232E308 to -4.94065645841247E-324 for negative values, and 4.94065645841247E-324 to 1.79769313486232E308 for positive values) applicable to a Double .

Example

Dim dblValue

dblValue = CDbl("5,579.56")

dblValue now holds the value 5579.56 or 5,57956, depending on the thousand and decimal separators in use.

See also

CBool , CByte , CCur , CInt , CLng , CSng , and CStr

Chr

Returns the ANSI character corresponding to character code.

Syntax

Chr(charactercode)

charactercode is a numeric value that indicates the character you want.

Note

Supplying a charactercode from 0 to 31 will return a standard nonprintable ASCII character.

Example

Dim strChar

strChar = Chr(89)

strChar now holds the character Y, which is number 89 in the ANSI character table.

See also

Asc , AscB , AscW , ChrB , and ChrW

ChrB

Returns the ANSI character corresponding to charactercode .

Syntax

ChrB(charactercode)

charactercode is a numeric value that indicates the character you want.

Note

Supplying a charactercode from 0 to 31 will return a standard nonprintable ASCII character. This function is used instead of the Chr (returns a 2-byte character) function when you want only the first byte of the character returned.

Example

Dim strChar

strChar = ChrB(89)

strChar now holds the character Y, which is number 89 in the ANSI character table.

See also

Asc , AscB , AscW , Chr , and ChrW

ChrW

Returns the Unicode character corresponding to charactercode .

Syntax

ChrW(charactercode) charactercode is a numeric value that indicates the character you want.

Note

Supplying a charactercode from 0 to 31 will return a standard nonprintable ASCII character. This function is used instead of the Chr function when you want to return a 2-byte character. It is for use on 32-bit Unicode enabled platforms only, to avoid conversion from Unicode to ANSI.

Example

Dim strChar

strChar = ChrW(89)

strChar now holds the character Y, which is number 89 in the Unicode character table.

See also

Asc , AscB , AscW , Chr , and ChrB

Cint

Returns an expression converted to Variant subtype Integer (2) .

Syntax

CInt(expression)

expression is any valid expression.

Note

CInt is internationally aware, which means that the return value is based on the locale settings on the machine. Please note that decimal values are rounded, before the fractional part is discarded. A runtime error occurs if expression lies outside the range (-32,768 to 32,767) applicable to an Integer .

Example

Dim intValue

intValue = CInt("5,579.56")

intValue now holds the value 5580, 6, 56, 558, or more, depending on the thousand and decimal separators in use.

See also

CBool , CByte , CCur , CDbl , CLng , CSng , CStr , and the math functions Fix and Int

CLng

Returns an expression converted to Variant subtype Long(3) .

Syntax

CLng(expression)

expression is any valid expression.

Note

CLng is internationally aware, which means that the return value is based on the locale settings on the machine. Please note that decimal values are rounded, before the fractional part is discarded. A runtime error occurs if expression lies outside the range (-2,147,483,648 to 2,147,483,647) applicable to a Long .

Example

Dim lngValue

lngValue = CLng("5,579.56")

lngValue now holds the value 5580, 6, 56, 558, or more, depending on the thousand and decimal separators in use.

See also

CBool , CByte , CCur , CDbl , CInt , CSng , CStr , and the math functions Fix and Int

CSng

Returns an expression converted to Variant subtype Single (4) .

Syntax

CSng(expression)

expression is any valid expression.

Note

CSng is internationally aware, which means that the return value is based on the locale settings on the machine. A runtime error occurs if expression lies outside the range (-3.402823E38 to -1.401298E-45 for negative values, and 1.401298E-45 to 3.402823E38 for positive values) applicable to a Single .

Example

Dim sngValue

sngValue = CSng('5,579.56')

sngValue now holds the value 5579.56 or 5,57956, depending on the thousand and decimal separators in use.

See also

CBool , CByte , CCur , CDbl , CInt , CLng , CStr , and the math functions Fix and Int

CStr

Returns an expression converted to Variant subtype String(8) .

Syntax

CStr(expression)

expression is any valid expression.

Note

CStr is internationally aware, which means that the return value is based on the locale settings on the machine. A runtime error occurs if expression is Null . Numeric and Err values are returned as numbers, Boolean values as True or False , and Date values as a short date.

Example

Dim strValue

strValue = CStr("5,579.56")

strValue now holds the value 5,579.56.

See also

CBool , CByte , CCur , CDbl , CInt , CLng , CSng , and the math functions Fix and Int

Fix

See under Math Functions

Hex

Returns the hexadecimal representation (up to 8 characters) of a number as a Variant subtype String(8) .

Syntax

Hex(number)

number is any valid expression.

Note

number is rounded to nearest even number before it is evaluated. Null will be returned if number is Null .

Example

Dim strValue

strValue = Hex(5579.56)

strValue now holds the value 15CC.

See also

Oct

Int

See under Math Functions

Oct

Returns the octal representation (up to 11 characters) of a number as a Variant subtype String(8) .

Syntax

Oct(number)

expression is any valid expression.

Note

number is rounded to nearest whole number before it is evaluated. Null will be returned if number is Null .

Example

Dim strValue

strValue = Oct(5579.56)

strValue now holds the value 12714.

See also

Hex


Unsupported Conversion Functions

The following VB/VBA conversion functions are not supported in VBScript.

Function Name Alternative

Cvar

Not needed since conversion to a Variant is implicit

CVDate

CDate , Date

Str

CStr

Val

CDbl , CInt , CLng , and CSng


Miscellaneous Functions, Statements, and Keywords

Some functionalities do not fit under any of the other categories, and so they have been gathered here.

In the following table you will find descriptions of various functions for handling objects, user input, variable checks, output on screen, and so on.

CreateObject

Returns a reference to an Automation/COM/ActiveX object. The object is created using COM object creation services.

Syntax

CreateObject( servername .typename[ , location])

servername is the name of the application that provides the object.

typename is the object's type or class that you want to create.

location (Optional) is the name of the network server you want the object created on. If this is missing the object is created on the local machine.

Note

An Automation/COM/ActiveX object always contains at least one type or class, but usually several types or classes are contained within. servername and typename are often referred to as progid . Note that a progid is not always a two part one, like servername.typename . It can have several parts , like servername.typename.version .

Example

Dim objRemote

Dim objLocal

' Create an object from class

' MyClass contained in the

' COM object MyApp on a

' remote server named FileSrv

Set objRemote = CreateObject( _

"MyApp.MyClass", "FileSrv")

' Create an object from class

' LocalClass contained in the

' COM object LocalApp on the

' local macine

Set objLocal = CreateObject( _

"LocalApp.LocalClass")

See also

GetObject

Dim

Declares a variable of type Variant and allocates storage space.

Syntax

Dim varname[([subscripts])][,

varname[([subscripts])]]

varname is the name of the variable

subscripts (Optional) indicates the dimensions when you declare an array variable. You can declare up to 60 multiple dimensions using the following syntax: upperbound[, upperbound]

upperbound specifies the upper bounds of the array. Since the lower bound of an array in VBScript is always zero, upperbound is one less than the number of elements in the array.

If you declare an array with empty subscripts, you can later resize it with ReDim; this is called a dynamic array.

Note

This statement is scope specific; that is, you need to consider when and where you want to declare your variables. Variables that are used only in a specific procedure should be declared in this procedure. This will make the variable invisible and inaccessible outside the procedure.

You can also declare your variables with script scope. This means that the variables will be accessible to all procedures within the script. This is one way of sharing data between different procedures.

Dim statements should be put at the top of a procedure to make the procedure easier to read.

Example

' Declare a dynamic array

Dim arrstrDynamic()

' Declare a fixed size array

' with 5 elements

Dim arrstrFixed(4)

' Declare a non-array variable

Dim vntTest

See also

ReDim and Set

Eval

Evaluates and returns the result of an expression.

Syntax

result = Eval(expression)

result (Optional) is the variable you want to assign the result of the evaluation to. Although result is optional, you should consider using the Execute statement, if you don't want to specify it.

expression is a string containing a valid VBScript expression.

Note

Because the assignment operator and the comparison operator are the same in VBScript, you need to be careful when using them with Eval . Eval always uses the equal sign ( = ) as a comparison operator; so if you need to use it as an assignment operator, you should use the Execute statement instead.

Example

Dim blnResult

Dim lngX, lngY

' Initialize the variables

lngX = 15: lngY = 10

' Evaluate the expression

blnResult = Eval( _

"lngX = lngY")

blnResult holds the value False , because 15 is not equal to 10.

See also

Execute

Execute

Executes one or more statements in the local namespace.

Syntax

Execute statement

statement is a string containing the statement(s) you want executed. If you include more than one statement, you must separate them using colons or embedded line breaks.

Note

Because the assignment operator and the comparison operator are the same in VBScript, you need to be careful when using them with Execute . Execute always uses the equal sign ( = ) as an assignment operator; so if you need to use it as a comparison operator, you should use the Eval function instead.

All in-scope variables and objects are available to the statement(s) being executed, but you need to be aware of the special case when your statements create a procedure.

Execute "Sub ExecProc: MsgBox ""In

here"": End Sub"

The scope of ExecProc is global and thus everything from the global scope is inherited. The context of the procedure itself is only available within the scope it is created. This means that if you execute the aforementioned Execute statement in a procedure, the ExecProc procedure will only be accessible within the procedure where the Execute statement is called. You can bypass this by simply moving the Execute statement to the script level or using the ExecuteGlobal statement.

Example

Dim blnResult

Dim lngX, lngY

' Initialize the variables

lngX = 15: lngY = 10

' Execute the statement

Execute("lngResult = + _

lngX + lngY")

lngResult holds the value 25.

See also

Eval and ExecuteGlobal

ExecuteGlobal

Executes one or more statements in the global namespace.

Syntax

ExecuteGlobal statement

statement is a string containing the statement(s) you want executed. If you include more than one statement, they need to be separated using colons or embedded line breaks.

Note

Because the assignment operator and the comparison operator are the same in VBScript, you need to be careful when using them with ExecuteGlobal . ExecuteGlobal always uses the equal sign ( = ) as an assignment operator; so if you need to use it as a comparison operator, you should use the Eval function instead.

 

All variables and objects are available to the statement(s) being executed.

Example

Dim lngResult

Dim lngX, lngY

' Initialize the variables

lngX = 15: lngY = 10

' Execute the statement

ExecuteGlobal("lngResult = + _

lngX + lngY")

lngResult holds the value 25.

See also

Eval and Execute

Filter

Returns an array that contains a subset of an array of strings. The array is zero-based as are all arrays in VBScript and it holds as many elements as are found in the filtering process. The subset is determined by specifying a criterion.

Syntax

Filter(inputstrings , value[ , include[ , compare]])

inputstrings is a one-dimensional string array that you want to search.

value is the string you want to search for.

include (Optional) is a Boolean value indicating if you want to include ( True ) or exclude ( False ) elements in inputstrings that contains value.

compare (Optional) indicates the comparison method used when evaluating. Use one of the following constants:

vbBinaryCompare -0 (Default) (Performs a binary comparison, that is, a case-sensitive comparison)

vbTextCompare -1 (Performs a textual comparison, that is, a non-case-sensitive comparison)

Note

An empty array is returned if no matches are found. A runtime error occurs if inputstrings is not a one-dimensional array or if it is Null .

Example

Dim arrstrColors(3)

Dim arrstrFilteredColors

' Fill the array

arrstrColors(0) = "Red"

arrstrColors(1) = "Green"

arrstrColors(2) = "Blue"

' Filter the array

arrstrFilteredColors = _

Filter(arrstrColors, "Red")

arrstrFilteredColors now holds one element ( ) which has the value Red .

See also

See the string function Replace

GetObject

Returns a reference to an Automation object.

Syntax

GetObject([pathname][ , class]])

pathname (Optional) is a string specifying the full path and name of the file that contains the object you want to retrieve. You need to specify class if you omit this argument.

class (Optional) is a string that indicates the class of the object. You need to specify pathname if you omit this argument. The following syntax is used for class:

appname .objecttype

appname is a string indicating the application that provides the object.

objecttype is a string specifying the object's type or class that you want created.

Note

You can use this function to start the application associated with pathname and activate/return the object specified in the pathname. A new object is returned if pathname is a zero-length string ('') and the currently active object of the specified type is returned if pathname is omitted. Note that if the object you want returned has been compiled with Visual Basic, you cannot obtain a reference to an existing object by omitting the pathname argument. A new object will be returned instead. The opposite is true for objects that are registered as single-instance objects; the same instance will always be returned. However, you should note the aforementioned problems with ActiveX DLLs compiled using Visual Basic.

Some applications allow you to activate part of a file and you can do this by suffixing pathname with an exclamation mark ( ! ) and a string that identifies the part of the object you want.

You should only use this function when there is a current instance of the object you want to create, or when you want the object to open up a specific document. Use CreateObject to create a new instance of an object.

Example

Dim myobj

Set myobj =

CreateObject("Excel.Application")

Dim objAutomation

' Create a reference to an

' existing instance of an

' Excel application (this

' call will raise an error

' if no Excel.Application

' objects already exists)

Set objAutomation = _

GetObject(, "Excel.Application")

' Create a reference to a

' specific workbook in a new

' instance of an Excel

' application

Set objAutomation = _

GetObject( "C:Test.xls ")

See also

CreateObject

GetRef

Returns a reference to a procedure. This reference can be bound to an object event. This will let you bind a VBScript procedure to a DHTML event.

Syntax

Set object.eventname = GetRef(procname)

object is the name of the object in which eventname is placed.

eventname is the name of the event to which the procedure is to be bound.

procname is the name of the procedure you want to bind to eventname .

Example

Sub NewOnFocus()

' Do your stuff here

End Sub

' Bind the NewOnFocus

' procedure to the

' Window. OnFocus event

Set Window.OnFocus = _

GetRef("NewOnFocus ")

InputBox

Displays a dialog box with a custom prompt and a text box. The content of the text box is returned when the user clicks OK .

Syntax

InputBox(prompt[ , title][ , default][ , xpos][ , ypos] , [helpfile , context])

prompt is the message you want displayed in the dialog box. The string can contain up to 1024 characters, depending on the width of the characters you use. You can separate the lines using one of these VBScript constants.

vbCr , vbCrLf , vbLf , or vbNewLine

title (Optional) is the text you want displayed in the dialog box title bar. The application name will be displayed, if this argument is omitted.

default is the default text that will be returned, if the user doesn't type in any data. The text box will be empty if you omit this argument.

xpos (Optional) is a numeric expression that indicates the horizontal distance of the left edge of the dialog box measured in twips (1/20 of a printer's point, which is 1/72 of an inch) from the left edge of the screen. The dialog box will be horizontally centered if you omit this argument.

ypos (Optional) is a numeric expression that indicates the vertical distance of the upper edge of the dialog box measured in twips from the upper edge of the screen. The dialog box will be vertically positioned approximately one third of the way down the screen, if you omit this argument.

helpfile (Optional) is a string expression that indicates the help file to use when providing context-sensitive help for the dialog box. This argument must be used in conjunction with context. This is not available on 16-bit platforms.

context (Optional) is a numeric expression that indicates the help context number that makes sure that the right help topic is displayed. This argument must be used in conjunction with helpfile . This is not available on 16-bit platforms.

Note

A zero-length string will be returned if the user clicks Cancel or presses Esc.

Example

Dim strInput

strInput = InputBox( _

"Enter User Name:", "Test")

MsgBox strInput

The MsgBox will display either an empty string or whatever the user entered into the text box.

See also

MsgBox

IsEmpty

Returns a Boolean value indicating if a variable has been initialized .

Syntax

IsEmpty(expression)

 

expression is the variable you want to check has been initialized.

Note

You can use more than one variable as expression. If, for example, you concatenate two Variant s and one of them is empty, the IsEmpty function will return False , because the expression is not empty.

Example

Dim strTest

Dim strInput

strInput = "Test"

MsgBox IsEmpty(strTest)          ' true

MsgBox IsEmpty(strInput & _

strTest)          ' false

See also

IsArray , IsDate , IsNull , IsNumeric , IsObject , and VarType

IsNull

Returns a Boolean value indicating if a variable contains Null or valid data.

Syntax

IsNull(expression)

expression is any expression.

Note

This function returns True if the whole of expression evaluates to Null . If you have more than one variable in expression, all of them must be Null for the function to return True .

Please be aware that Null is not the same as Empty (a variable that hasn't been initialized) or a zero-length string (''). Null means no valid value.

You should always use the IsNull function when checking for Null values, because using the normal operators will return False even if one variable is Null .

Example

Dim strInput

strInput = "Test"

MsgBox IsNull( strInput _

& Null) ˜ false

MsgBox IsNull(Null) ƒ' true

See also

IsArray , IsDate , IsEmpty , IsNumeric , IsObject , and VarType

IsNumeric

Returns a Boolean value indicating if an expression can be evaluated as a number.

Syntax

IsNumeric(expression)

expression is any expression.

Note

This function returns True if the whole expression evaluates to a number. A Date expression is not considered a numeric expression.

Example

MsgBox IsNumeric(55.55)

' true

MsgBox IsNumeric("55.55")

' true

MsgBox IsNumeric("55.55aaa")

' false

MsgBox IsNumeric( "March 1, 1999")

' false

MsgBox IsNumeric(vbNullChar)

' false

See also

IsArray , IsDate , IsEmpty , IsNull , IsObject , and VarType

IsObject

Returns a Boolean value indicating if an expression is a reference to a valid Automation object.

Syntax

IsObject(expression)

expression is any expression.

Note

This function returns True only if expression is in fact a variable of Variant subtype Object (9) or a user-defined object.

Example

Dim objTest

MsgBox IsObject(objTest)

' false

Set objTest = CreateObject( _

"Excel.Application")

MsgBox IsObject(objTest)

' true

See also

IsArray , IsDate , IsEmpty , IsNull , IsNumeric , Set , and VarType

LoadPicture

Returns a picture object.

Syntax

LoadPicture(picturename)

picturename is a string expression that indicates the filename of the picture you want loaded.

Note

This function is available only on 32-bit platforms.

The following graphic formats are supported:

Bitmap - .bmp

Icon - .ico

Run-length encoded - .rle

Windows metafile - .wmf

Enhanced metafile - .emf

GIF - .gif

JPEG - .jpg

A runtime error occurs if picturename doesn't exist or if it is not a valid picture file. Use LoadPicture("") to return an 'empty' picture object in order to clear a particular picture.

Example

Dim objPicture

' Load a picture into

' objPicture

objPicture = LoadPicture( _

"C:Test.bmp")

' Clear objPicture

objPicture = LoadPicture("")

MsgBox

Displays a dialog box with a custom message and a custom set of command buttons . The value of the button the user clicks is returned as the result of this function.

Syntax

MsgBox(prompt[ , buttons][ , title [ , helpfile , context])

prompt is the message you want displayed in the dialog box. The string can contain up to 1024 characters, depending on the width of the characters you use.

You can separate the lines using one of these VBScript constants.

vbCr , vbCrLf , vbLf , or vbNewLine

buttons (Optional) is the sum of values indicating the number and type of button(s) to display, which icon style to use, which button is the default, and if the MsgBox is modal.

The settings for this argument are:

vbOKOnly -0 (Displays OK button)

vbOKCancel -1 (Displays OK and Cancel buttons)

vbAbortRetryIgnore -2 (Displays Abort , Retry , and

Ignore buttons)

vbYesNoCancel -3 (Displays Yes , No , and Cancel buttons)

vbYesNo -4 (Displays Yes and No buttons)

vbRetryCancel -5 (Displays Retry and Cancel buttons)

vbCritical -16 (Displays critical icon)

vbQuestion -32 (Displays query icon)

vbExclamation -48 (Displays warning icon)

vbInformation -64 (Displays information icon)

vbDefaultButton1 -0 (Makes the first button the default one)

vbDefaultButton2 -256 (Makes the second button the default one)

vbDefaultButton3 -512 (Makes the third button the default one)

vbDefaultButton4 -768 -(Makes the fourth button the default one)

vbApplicationModal -0 (When the MsgBox is application modal, the user must respond to the message box, before he or she can continue)

vbSystemModal -4096 (The same effect as vbApplicationModal )

Buttons (values 0-5)

Icon (values 16, 32, 48, and 64)

Default button (values 0, 256, 512, and 768)

Modal (values 0 and 4096)

You should only pick one value from each group when creating your MsgBox .

title (Optional) is the text you want displayed in the dialog box title bar. The application name will be displayed if this argument is omitted.

helpfile (Optional) is a string expression that indicates the help file to use when providing context-sensitive help for the dialog box. This argument must be used in conjunction with context. This is not available on 16-bit platforms.

context (Optional) is a numeric expression that indicates the help context number that makes sure that the right help topic is displayed. This argument must be used in conjunction with helpfile .

Note

The following values can be returned:

vbOK (1)

vbCancel(2)

vbAbort (3)

vbRetry (4)

vbIgnore (5)

vbYes (6)

vbNo (7)

The Esc key has the same effect as the Cancel button. Clicking the Help or pressing F1 will not close the MsgBox .

Example

Dim intReturn

intReturn = MsgBox( "Exit the _

application?", vbYesNoCancel + _

vbQuestion)

The MsgBox will display the message "Exit the application?" , the buttons Yes , No , and Cancel , and the question mark icon. This MsgBox will be application modal.

See also

InputBox

RGB

Returns an integer that represents an RGB color value.

The RGB color value specifies the relative intensity of red, green, and blue to cause a specific color to be displayed.

Syntax

RGB(red , green , blue)

red is the red part of the color. Must be in the range 0-255.

green is the green part of the color. Must be in the range 0-255.

blue is the blue part of the color. Must be in the range 0-255.

Note

255 will be used, if the value for any of the arguments is larger than 255. A runtime error occurs if any of the arguments cannot be evaluated to a numeric value.

Example

' Returns the RGB number for white

RGB(255, 255, 255)

ScriptEngine

Returns a string indicating the scripting language being used.

Syntax

ScriptEngine

Note

The following scripting engine values can be returned:

VBScript MS VBScript

JScript ƒ MS JScript

VBA ƒ ƒ ƒ MS Visual Basic for Applications Other third-party ActiveX Scripting engines can also be returned, if you have installed one.

See also

ScriptEngineBuildVersion ,

ScriptEngineMajorVersion , and

ScriptEngineMinorVersion

ScriptEngineBuildVersion

Returns the build version of the script engine being used.

Syntax

ScriptEngineBuildVersion

Note

This function gets the information from the DLL for the current scripting language.

See also

ScriptEngine , ScriptEngineMajorVersion , and ScriptEngineMinorVersion

ScriptEngineMajorVersion

Returns the major version number of the script engine being used. The major version number is the part before the decimal separator, for example 5 if the version is 5.6.

Syntax

ScriptEngineMajorVersion

Note

This function gets the information from the DLL for the current scripting language.

See also

ScriptEngine , ScriptEngineBuildVersion , and ScriptEngineMinorVersion

ScriptEngineMinorVersion

Returns the minor version number of the script engine being used. The minor version number is the part after the decimal separator, for example 6 if the version is 5.6.

Syntax

ScriptEngineMinorVersion

Note

This function gets the information from the DLL for the current scripting language.

See also

ScriptEngine , ScriptEngineBuildVersion , and ScriptEngineMajorVersion

Set

Returns an object reference, which must be assigned to a variable or property, or returns a procedure reference that must be associated with an event.

Syntax

Set objectvar = objectexpression New classname Nothing

objectvar is the name of a variable or property.

objectexpression (Optional) is the name of an existing object or another variable of the same object type. It can also be a method or function that returns either.

classname (Optional) is the name of the class you want to create.

Set object.eventname = GetRef(procname)

object is the name of the object that eventname is associated with.

eventname is the name of the event you want to bind procname to.

procname is the name of the procedure you want to associate with eventname.

Note

objectvar must be an empty variable or an object type consistent with objectexpression being assigned.

Set is used to create a reference to an object and not a copy of it. This means that if you use the Set statement more than once on the same object, you will have more than one reference to the same object. Any changes made to the object will be 'visible' to all references. New is used only in conjunction with classname , when you want to create a new instance of a class

If you use the Nothing keyword, you release the reference to an object, but if you have more than one reference to an object, the system resources are released only when all references have been destroyed (by setting them to Nothing ) or they go out of scope.

Example

Dim objTest1

Dim objTest2

Dim objNewClass

' Create a new dictionary object

Set objTest1 = CreateObject( _

"Scripting.Dictionary")

' Create a reference to the

' newly created dictionary

' object

Set objTest2 = objTest1

' Destroy the object reference

Set objTest1 = Nothing

' Although objTest2 was set

' to refer to objTest1, you can

' still refer to objTest2,

' because the system resources

' will not be released before

' all references have been

' destroyed. So let's add a key

' and an item

objTest2.Add "TestKey", "Test"

' Destroy the object reference

Set objTest2 = Nothing

' Create an instance of the

' class clsTest (created with

' the Class keyword)

Set objNewClass = New clsTest

' ...

' Destroy the class instance

Set objNewClass = Nothing

See also

Class and GetRef

TypeName

Returns the Variant subtype information for an expression as a Variant subtype String(8) .

Syntax

TypeName(expression)

expression is the variable or constant you want subtype information for.

Note

This function has the following return values (strings):

Byte - Byte

Integer - Integer

Long - Long integer

Single - Single-precision floating-point number

Double - Double-precision floating-point number

Currency - Currency

Decimal - Decimal

Date - Date and/or time

String - Character string

Boolean - True or False

Empty - Unitialized

Null - No valid data

< object type > - Actual type name of an object

Object - Generic object

Unknown - Unknown object type

Nothing - Object variable that doesn't refer to an object instance

Error - Error

Example

Dim arrstrTest(10)

MsgBox TypeName(10)

' Integer

MsgBox TypeName("Test")

' String

MsgBox TypeName(arrstrTest)

' Variant()

MsgBox TypeName(Null)

' Null

See also

IsArray , IsDate , IsEmpty , IsNull , IsNumeric , IsObject , and VarType

VarType

Returns an integer indicating the subtype of a variable or constant.

Syntax

VarType(expression)

expression is the variable or constant you want subtype information for.

Note

This function has the following return values:

vbEmpty -0 (Uninitialized)

vbNull -1 (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 (only used only with arrays of Variants))

vbDataObject -13 (A data-access object)

vbByte -17 (Byte)

vbArray -8192 (Array)

Example

Dim arrstrTest(10)

MsgBox VarType(10)

' 2

MsgBox VarType("Test")

' 8

MsgBox VarType(arrstrTest)

' 8204

MsgBox VarType(Null)

' 1

See also

IsArray , IsDate , IsEmpty , IsNull , IsNumeric , IsObject , and TypeName




VBScript Programmer's Reference
VBScript Programmers Reference
ISBN: 0470168080
EAN: 2147483647
Year: 2003
Pages: 242

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net