This is a reference of functions and keywords in VBScript 5, VB, and VBA
     
     
   

VBScript Functions and Keywords (also includes VB and VBA)

  Overview
  Operators
  Assignment Operator
  Arithmetic Operators
  Concatenation Operators
  Comparison Operators
  Logic Operators
    --- Not
    --- And
    --- Or
    --- Xor
    --- Eqv
    --- Imp
  Bitwise Operators
    --- Not
    --- And
    --- Or
    --- Xor
    --- Eqv
    --- Imp
  Operator Precedence
  Unsupported Operators (VB/VBA only)
  Math Functions
    --- Abs
    --- Atn
    --- Cos
    --- Exp
    --- Fix
    --- Int
    --- Log
    --- Randomize
    --- Rnd
    --- Round
    --- Sgn
    --- Sin
    --- Sqr
    --- Tan
  Date and Time Functions and Statements
    --- CDate
    --- Date
    --- DateAdd
    --- DateDiff
    --- DatePart
    --- DateSerial
    --- DateValue
    --- Day
    --- Hour
    --- IsDate
    --- Minute
    --- Month
    --- MonthName
    --- Now
    --- Second
    --- Time
    --- Timer
    --- TimeSerial
    --- TimeValue
    --- Weekday
    --- WeekdayName
    --- Year
  Unsupported Date Functions and Statements (VB/VBA only)
  Array Functions and Statements
    -- Array
    -- Erase
    -- For Each
    -- IsArray
    -- LBound
    -- ReDim
    -- UBound
  Unsupported Array Functions and Statements (VB/VBA only)
  String Functions and Statements
    -- FormatCurrency
    -- FormatDateTime
    -- FormatNumber
    -- FormatPercent
    -- InStr
    -- InstrB
    -- InStrRev
    -- Join
    -- LCase
    -- Left
    -- Len
    -- LenB
    -- LTrim
    -- Mid
    -- MidB
    -- Replace
    -- Right
    -- RTrim
    -- Space
    -- Split
    -- StrComp
    -- String
    -- StrReverse
    -- Trim
    -- UCase
  Unsupported String Functions, Statements and Constructs (VB/VBA only)
  String Constants
  Conversion Functions
    -- Asc
    -- AscB
    -- AscW
    -- CBool
    -- CByte
    -- CCur
    -- CDbl
    -- Chr
    -- ChrB
    -- ChrW
    -- CInt
    -- CLng
    -- CSng
    -- CStr
    -- Hex
    -- Oct
  Unsupported Conversion Functions (VB/VBA only)
  Miscellaneous Functions Statements and Keywords
  --- CreateObject
  --- Dim
  --- Eval
  --- Execute
  --- ExecuteGLobal
  --- Filter
  --- GetObject
  --- GetRef
  --- InputBox
  --- IsEmpty
  --- IsNull
  --- IsNumeric
  --- IsObject
  --- LoadPicture
  --- MsgBox
  --- RGB
  --- ScriptEngine
  --- ScriptEngineBuildVersion
  --- ScriptEngineMajorVersion
  --- ScriptEngineMinorVersion
  --- TypeName
  --- VarType
     
   

VBScript Functions and Keywords

Overview

This Appendix contains a complete reference of functions and keywords in VBScript 5. 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.

 

The function and keyword references are grouped in categories and they include the full syntax, an explanation, notes, sample code, and a "See also" list. The function references also include a list of named constants and their values.

 

Please note that there are a number of VB constructs, which are not supported in VBScript. This includes File I/O (for security reasons), the Debug and Collection objects, some conversion functions, and the complete set of financial functions. For a complete list, see "Differences Between VB/VBA and VBScript" towards the end of this Appendix.

   
Top of Page

Operators

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

 

Say, you want to calculate the difference between two variables A and B and save the result in variable C. These variables are the operands and to find the difference you use the subtraction operator like this:

C = A – B

Here we used the assignment operator (=) to assign the difference between A and B, which was found by using the subtraction operator (-).

Operators are one of the single-most important parts of any programming language. Without them, you would not be able to assign values to variables or perform calculations and comparisons! It would be a bit like a bicycle without pedals...

 

There are different types of operators and they each serve a specific purpose, as you will see from the following.

   
Top of Page

 

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

 

Description

 

 

Syntax

Assignment

 

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

 

 Variable = value

   
Top of Page

 

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

 

Description

 

Syntax

 

 

 

Example

Exponentiation

 

Raises a number to the power of an exponent.

 

Result = number ^ exponent

 

number and exponent is any valid numeric expression.

 

    MsgBox 5 ^ 5

 

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

 

Top of Page

*

Name

 

Description

 

Syntax

 

 

 

Example

 

Multiplication

 

Multiplies two numbers.

 

Result = number1 * number2

 

number1 and number2 is any valid numeric expression.

 

   MsgBox 5 * 5

 

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

 

Top of Page

/

Name

 

Description

 

Syntax

 

 

 

Example

Floating Point Division

 

Returns a floating point result when dividing two numbers.

 

Result = number1 / number2

 

number1 and number2 is any valid numeric expression.

 

   MsgBox 5 / 4

 

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

 

Top of Page

\

Name

 

Description

 

Syntax

 

 

 

Example

 

 

 

 Note

 

 

Integer Division

 

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

 

Result = number1 \ number2

 

number1 and number2 is any valid numeric expression.

 

   MsgBox 5 \ 4

 

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

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, i.e. a value of 255 will be    rounded to a Byte, and 256 will be rounded to an Integer and so on.

 

Top of Page

Mod

Name

 

Description

 

Syntax

 

 

 

Example

 

 

 

Note

 

Modulus Division

 

Returns the remainder when dividing two numbers.

 

Result = number1 Mod number2

 

number1 and number2 is any valid numeric expression.

 

   MsgBox 5 Mod 4

 

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

 

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, i.e. a value of 255 will be rounded to a Byte, and 256 will be rounded to an Integer and so on.

 

Top of Page

+

Name

 

Description

 

Syntax

 

 

 

Example

 

 

 

 Note

 

Addition

 

Sums two expressions.

 

Result = expression1 + expression2

 

expression1 and expression2 is any valid numeric expression.

 

   MsgBox 5 + 5

 

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

 

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.

 

Top of Page

-

Name

 

Description

 

Syntax (1)

 

 

 

Example (1)

 

 

 

 Syntax (2)

 

 

 

Example (2)

Subtraction

 

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

 

Result = number1 – number2

 

number1 and number2 is any valid numeric expression.

 

   MsgBox 5 - 4

 

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

 

-number

 

number is any valid numeric expression.

 

   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.

   
Top of Page

 

Concatenation operators

Concatenation operators are used for concatenating expressions; they are listed in order of Operator Precedence.

 

&

Name

 

Description

 

Syntax

 

 

 

Example

 

 

 Note

 

Ampersand

 

Concatenates two expressions.

 

Returns the concatenated expressions:

 

Result = expression1 & expression2

 

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

 

 

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

 

Top of Page

+

Name

 

Description

 

Syntax

 

 

 

Example

 

 

Note

     

 

+ Operator

 

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

 

Returns the concatenated or summed expressions:

 

Result = expression1 + expression2

 

1 + "1" = 2

"1" + "1" = "11"

 

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 only be used for numeric addition and never for concatenation purposes (use & instead).

   
Top of Page

 

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.

 

One important thing to remember when comparing strings is case sensitivity. You can use the UCase and LCase functions to make sure that the strings you compare are the same case; the StrComp function offers another way of dealing with case sensitivity (see under String Functions). In VB/VBA you have the Option Compare statement, but this is not supported in VBScript. So keep in mind, when using the operators listed below, that if you compare strings (when both expressions are strings), a binary comparison is performed on the sequences of characters. A binary comparison is always case sensitive. If only one of the expressions is a string and the other is numeric, the numeric expression is always less than the string expression.

 

Null is returned if either expression is Null. If either expression is Empty, it is converted to the value 0, if the other expression is numeric and to an empty string (""), if the other expression is a string. In case both expressions are Empty, they are obviously equal.

 

The Is operator is for dealing with objects and Variants.

 

=

Name

 

Description

 

Syntax

 

Equal to

 

Returns true if expression1 is equal to expression2; false otherwise.

 

Result = expression1 = expression2

 

Top of Page

<> 

Name

 

Description

 

Syntax

 

Not equal to (different from)

 

Returns true if expression1 is not equal to expression2; false otherwise.

 

Result = expression1 <> expression2

 

Top of Page

Name

 

Description

 

Syntax

Less than

 

Returns true if expression1 is less than expression2; false otherwise.

 

Result = expression1 < expression2

 

Top of Page

Name

 

Description

 

Syntax

Greater than

 

Returns true if expression1 is greater than expression2; false otherwise.

 

Result = expression1 > expression2

 

Top of Page

<=

Name

 

Description

 

Syntax

Less than or equal to

 

Returns true if expression1 is less than or equal to expression2; false otherwise.

 

Result = expression1 <= expression2

 

Top of Page

>=

Name

 

Description

 

Syntax

Greater than or equal to

 

Returns true if expression1 is greater than or equal to expression2; false otherwise.

 

Result = expression1 >= expression2

 

Top of Page

Is

Name

 

Description

 

 

Syntax

 

Note

Compare objects

 

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

 

Result = object1 Is object2

 

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.

   
Top of Page

 

   

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 BitwiseOperators).

 

 

Not

Used to

 

Returns

 

Syntax

 

Note

 

Negate the expression.

 

Returns the logical negation of an expression.

 

Result = Not expression

 

Result will be true if expression is false; and false if expression is true. Null will be returned if expression is Null.

 

Top of Page

And

Used to

 

Returns

 

Syntax

Check if both expressions are true.

 

Returns true if both expressions evaluate to true; otherwise, false is returned.

 

Result = expression1 And expression2

 

Top of Page

Or

Used to

 

Returns

 

Syntax

Check if one or both expressions are true.

 

Returns true if one or both expressions evaluate to true; otherwise, false is returned.

 

Result = expression1 Or expression2

 

Top of Page

Xor

Used to

 

Returns

 

Syntax

 

Note

Check if one and only one expression is true.

 

Null will be returned if either expression is Null.

 

Result = expression1 Xor expression2

 

Returns true if only one of the expressions evaluates to true; otherwise, false is returned.

 

Top of Page

Eqv

Used to

 

Returns

 

Syntax

 

Note

Check if both expressions evaluate to the same value.

 

Returns true if both expressions evaluate to the same value (true or false).

 

Result = expression1 Eqv expression2

 

Null will be returned if either expression is Null.

 

Top of Page

Imp

Used to

 

Returns

 

 

 

 

 

 

 

 

 

  Syntax

 

Perform a logical implication.

 

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

 

Result = expression1 Imp expression2

   
Top of Page

 

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 LogicalOperators).

Not

Used to

 

Returns

 

Syntax

 

 

Invert the bit values.

 

Returns 1 if bit is 0 and vice versa.

 

Result = Not expression

 

If expression is 101 then result is 010.

 

Top of Page

And

Used to

 

Returns

 

Syntax

 

 

Check if both bits are set to 1.

 

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

 

Result = expression1 And expression2

 

If expression1 is 101 and expression2 is 100 then result is 100.

 

Top of Page

Or

Used to

 

Returns

 

Syntax

 

 

Check if one of the bits is set to 1.

 

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

 

Result = expression1 Or expression2

 

If expression1 is 101 and expression2 is 100 then result is 101.

 

Top of Page

Xor

Used to

 

Returns

 

Syntax

 

Checks if one and only one of the bits are set to 1.

 

Returns 1 if only one bit is 1; otherwise, 0 is returned.

 

Result = expression1 Xor expression2

 

If expression1 is 101 and expression2 is 100 then result is 001.

 

Top of Page

Eqv

Used to

 

Returns

 

Syntax

 

Checks if both bits evaluate to the same value.

 

Returns 1 if both bits evaluate to the same value (0 or 1).

 

Result = expression1 Eqv expression2

 

If expression1 is 101 and expression2 is 100 then result is 110.

 

Top of Page

Imp

Used to

 

Returns

 

 

 

 

 

 

Syntax

 

Performs a logical implication on two bits.

 

Returns these values:

 

0 Imp 0          =           1

0 Imp 1          =          1

1 Imp 1          =           1

1 Imp 0          =           0

 

Result = expression1 Imp expression2

 

If expression1 is 101 and expression2 is 100 then result is 110.

   
Top of Page

 

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, 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.

   
Top of Page

 

Unsupported operators

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

 

Like

   
Top of Page

 

Math Functions

Every now and then, depending on what kind of applications you design, you will need to do some math calculations and VBScript goes a long way towards helping you here. There are a number of intrinsic functions, but it is also possible to derive many other math functions from the intrinsic ones. Math functions are especially helpful when you need to display graphics, charts etc; the listing is in alphabetical order.

 

Abs

Returns the absolute value of a number, i.e. 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

 

Top of Page

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 -pi/2 to pi/2 radians.

 

Example

Dim dblPi

          ' Calculate the
          ' value of Pi
          dblPi = 4 * Atn(1)

 

See Also

Cos, Sin and Tan

 

Top of Page

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.

 

Example

Dim dblAngle, dblSecant
Dim dblLength

   dblLength = 10
          ' Convert 30° to radians
   dblAngle = (30 * 3.14 / 180)
   dblSecant = dblLength / Cos(dblAngle) 

 

Here the Cos function is used to return the cosine of an angle.

 

See Also

Atn, Sin and Tan

 

Top of Page

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

 

Top of Page

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, and 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 non-negative numbers. When you handle negative numbers, Fix returns the first negative integer, greater than, or equal to the number supplied.

 

See Also

Int, Round and the

Conversion Functions CInt and CLng

 

Top of Page

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, and 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 non-negative 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

 

Top of Page

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)

 

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

 

See Also

Exp

Top of Page

Randomize

Initilizes 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

 

The above 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

 

Top of Page

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:

 

< 0 – usessame number every time,

> 0 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

 

Top of Page

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, 2)    ' Returns 10.4
Round(10.456, 2)  ' Returns 10.46
Round(-10.456, 2) ' Returns –10.46

See Also

Int and Fix

 

Top of Page

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

 

Top of Page

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 function is used to return the sine of an angle.

 

See Also

Atn, Cos and Tan

 

Top of Page

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

Top of Page

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 Sin

   
Top of Page

 

 

   

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 only lets you use the US-English 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/1997# will be interpreted as October 12, 1997, but you might in fact want December 10, 1997, because your locale settings interprets dates as dd/mm/yyyy. Date literals only accept 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.

 

Below 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/1997#)

 

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

 

See Also

IsDate

Top of Page

Date

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

Syntax

 

Date

Example

 

MsgBox Date

 

Assuming that today is July 29 1999, the MsgBox now displays 29-07-99, 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

Top of Page

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 precedes the year 100.

 

Example

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

 

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

 

See Also

DateDiff, DatePart

Top of Page

DateDiff

Returns the interval between two dates.

 

Syntax

 

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 year

yyyy               Year

 

date1 and date2 are date expressions.

 

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

vbUseSystemDayOfWeek      0     (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.)

vbSunday                                1 (default)

vbMonday                               2

vbTuesday                               3

vbWednesday                          4

vbThursday                             5

vbFriday                                  6

vbSaturday                              7

 

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 four 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", #11-22-1967#, Now)

 

This will calculate the number of years between 11/22/1967 and now. In 1999, the MsgBox will display 32.

See Also

DateAdd, DatePart

Top of Page

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

ww                 Week 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)

vbSunday                                          1 (default)

vbMonday                                         2

vbTuesday                                         3

vbWednesday                                   4

vbThursday                                       5

vbFriday                                            6

vbSaturday                                        7

 

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 four 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, 1999 the MsgBox will display 30.

 

See Also

DateAdd, DateDiff

Top of Page

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 one 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 – 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( 1999, 07, 29)

 

The MsgBox will display 29-07-99", 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

Top of Page

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 – 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("07/29/1999")
DateValue("July 29, 1999")
DateValue("Jul 29, 1999")
DateValue("Jul 29")

 

All of the above will return the same valid date of 07/29/99.

 

See Also

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

Top of Page

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("July 29, 1999")

 

The MsgBox will display 29.

 

See Also

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

Top of Page

FormatDateTime

See under Stringfunctions

 

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

Top of Page

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(#7/29/1999#) ' true

 

See Also

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

Top of Page

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

 

Top of Page

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

Top of Page

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

Top of Page

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

Top of Page

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

Top of Page

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, Now

Top of Page

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

 

Top of Page

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 one 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 – 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

Top of Page

TimeValue

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

 

Syntax

 

TimeValue(time)

 

time is an expression in the range 0:00:00 – 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, Weekday and Year

Top of Page

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)

vbSunday                                          1 (Default)

vbMonday                                         2

vbTuesday                                         3

vbWednesday                                   4

vbThursday                                       5

vbFriday                                            6

vbSaturday                                        7

 

Note

 

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

 

vbSunday                                          1

vbMonday                                         2

vbTuesday                                         3

vbWednesday                                   4

vbThursday                                       5

vbFriday                                            6

vbSaturday                                        7

 

Example

Weekday(#July 29, 1999#)

 

Returns 5 for Thursday.

 

See Also

Date, Day, Month, Now and Year

Top of Page

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

Top of Page

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(#7/29/1999#)

 

The MsgBox will display 1999.

 

See Also

Date, Day, Month, Now and Weekday

   
Top of Page

 

 

   

Unsupported Date Functions and Statements

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

 

Function/Statement Name

Alternative

Date statement

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

Time statement

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

   
Top of Page

 


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. Below 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( _
                    "Element0", "Element1", "Element2")
   ' Show the first list element
   ' now in the array
   MsgBox arrstrTest(0)

 

MsgBox displays Element0

 

See Also

Dim statement

Top of Page

Erase

Reinitializes the elements if it is a fixed-size array and de-allocates 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 de-allocated when using Erase with dynamic arrays, you must re-declare 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 0.
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 statement and ReDim statement

Top of Page

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( "Element0", "Element1", "Element2")
          ' Loop through the array
          For Each strElement In arrstrLoop
                    ' Display the element content
                    MsgBox strElement
          Next

Top of Page

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 rocks!"
          MsgBox IsArray( strName)     ' false
          MsgBox IsArray( arrstrFixed) ' true

 

See Also

IsDate, IsEmpty, IsNull, IsNumeric, IsObject and VarType

Top of Page

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 statement, ReDim statement and UBound

Top of Page

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 zero.

 

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(3)
            ' 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 3 element
            MsgBox arrstrDynamic(2)

 

MsgBox displays 3.

 

See Also

Dim statement and Set statement

Top of Page

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 statement, UBound  and ReDim statement

   
Top of Page

 

 

Unsupported Array functions and Statements

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

 

Option Base

 

   
Top of Page

 


String Functions and Statements

Whatever your application does, you are likely to use string manipulation. By string manipulation we mean things like extracting a name from a string, checking if a particular string is part of another string, formatting numbers as strings with delimiters, and so on. Below is a list of the various string functions in VBScript.


Some functionality is not exposed as functions, but as methods of objects. For example, the RegExp object exposes regular expression support. See chapter 7 The Built-In and Scripting Runtime Objects.

 

FormatCurrency

Formats an expression as a currency value with the current currency symbol. The currency symbol is defined in Regional Settings in the 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, after the number, is there a space between the symbol and the number and so on.)

 

Example

MsgBox FormatCurrency(7500)
MsgBox FormatCurrency(7500, , vbtrue)
MsgBox FormatCurrency(7500, 2, vbtrue)

 

If the currency symbol is a pound 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.00 in all of the above statements.

 

See Also

FormatDateTime, FormatNumber and FormatPercent

Top of Page

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    0  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 July 29, 1999 the MsgBox will display 07/29/99, 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

Top of Page

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:


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 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

Top of Page

FormatPercent

Returns a string formatted as a percentage, like 50%.

 

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:


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 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

Top of Page

InStr

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

 

Syntax

 

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

 

start (Optional) is any valid non-negative expression indicating the starting position for the search within string1. Non-integer 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 sub string 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, i.e. a case sensitive comparison.
vbTextCompare          1 Performs a textual comparison, i.e. 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           0

string1          Null                       Null

string2          zero-length           start

string2          Null                       Null

string2          not found              0

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 > 0

      ' 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

 

The above 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, InStrRev

Top of Page

InStrB

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

 

Syntax

 

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

 

start (Optional) is any valid non-negative expression indicating the starting position for the search within string1. Non-integer 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 sub string 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, i.e. a case sensitive comparison.
vbTextCompare – 1 Performs a textual comparison, i.e. 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          0

string1          Null                      Null

string2          zero-length          start

string2          Null                      Null

string2          not found             0

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 > 0
      ' 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

 

The above 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 non-zero value.

 

See Also

InStr, InStrRev

Top of Page

InStrRev

Returns an integer indicating the position of the first occurrence of a sub string 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 sub string you want to search for.

 

start (Optional) is any valid non-negative 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, i.e. a case sensitive comparison.
vbTextCompare – 1 Performs a textual comparison, i.e. a non-case sensitive comparison.

 

Note

 

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

 

Possible return values for different stringx settings:

string1          zero-length          0

string1          Null                      Null

string2          zero-length          start

string2          Null                      Null

string2          not found            0

string2          found                   Position

 

InStrRev and InStr do not have 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 = InStrRev( strSearchWithin, strSearchFor, lngStartPos)

   ' Loop through the string
   Do While lngFoundPos > 0
      ' 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 = InStrRev( strSearchWithin, strSearchFor, lngStartPos)
   Loop

 

The above 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, InStrB

Top of Page

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

Top of Page

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

Top of Page

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

Top of Page

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

Top of Page

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

Top of Page

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

 

Top of Page

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

 

Top of Page

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

Top of Page

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, i.e. a case sensitive comparison.
 vbTextCompare – 1 Performs a textual comparison, i.e. 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

Top of Page

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, Midand MidB

Top of Page

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

 

Null is returned if string contains Null.

 

Example

Dim strSpaces

          strSpaces = "* Hello again   "
          MsgBox RTrim(strSpaces)

 

MsgBox displays  * Hello again

 

See Also

Left, LTrim, Mid, Right and Trim

Top of Page

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

Top of Page

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, i.e. a case sensitive comparison.
vbTextCompare – 1 Performs a textual comparison, i.e. 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, 0,1,2...0.

 

See Also

Join

Top of Page

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, i.e. a case sensitive comparison.
 vbTextCompare – 1 Performs a textual comparison, i.e. 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

Top of Page

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 String(5, "*") & strChars

 

MsgBox displays  *****Hello again

 

See Also

Space

Top of Page

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

 

Top of Page

Trim

Trims a string of leading and trailing spaces; " " or Chr(20).

 

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

Top of Page

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

   
Top of Page

 

 

   

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, FormatPercent

 

LSet

Left, Len and Space functions in conjunction:

 

Dim strTest
Dim strNewText

          ' strTest is now 5 chars wide
   strTest = "01234"
          ' Assign the text to left align
   strNewText = "<-Test"
          ' Use the VB/VBA LSet (Unsupported)
   LSet strTest = strNewText

          ' Check if the New Text is wider than
          ' the variable we will align it in
   If Len(strNewText) <= Len(strTest) Then
                    ' Copy the text across and pad the
                    ' rest with spaces
       strTest = strNewText & Space(Len(strTest) - Len(strNewText))
   Else
                    ' Copy as many chars from the new
                    ' text as strTest is wide
                strTest = Left(strNewText, Len(strTest))
   End If

 

In both cases strTest will hold the value "<-Tes", because the original string strTest is only 5 characters wide and thus cannot hold all of strNewText. Had strTest been larger, the remaining places would have been filled with spaces.

 

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

 

RSet

Left, Len and Space functions in conjunction:

Dim strTest
Dim strNewText

          ' strTest is now 5 chars wide
   strTest = "01234"
          ' Assign the text to right align
   strNewText = "Test->"
          ' Use the VB/VBA RSet (Unsupported)
   RSet strTest = strNewText

          ' Check if the New Text is wider than
          ' the variable we will asign it in
   If Len(strNewText) <= Len(strTest) Then
                    ' Pad with spaces and copy the
                    ' text across
       strTest = Space(Len(strTest) - Len(strNewText)) & strNewText
   Else
                    ' Copy as many chars from the new
                    ' text as strTest is wide
        strTest = Left(strNewText, Len(strTest))
   End If

 

In both cases strTest will hold the value "Test-", because the original string strTest is only 5 characters wide and thus cannot hold all of strNewText. Had strTest been larger, the remaining places would have been filled with spaces.

 

StrConv

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.

   
Top of Page

 

 

String constants

Constant

Value

Description

vbCr

Chr(13)

Carriage Return.

 

vbCrLf

Chr(13) & Chr(10)

A combination of Carriage Return and linefeed.

 

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.

   
Top of Page

 


Conversion Functions

Normally you don't need to convert values in VBScript, because there is only one data type, the Variant.

 

Implicit conversion is generally applied when needed, but when you pass a value to a non-variant procedure in a COM object that needs the value passed ByRef, you will have to pass the value with the precise data subtype. This can be done by placing the argument in it's own set of parentheses, which forces a temporary evaluation of the argument as an expression:

 

Dim objByRefSample

Dim intTest

   ' Initialize the variable

   intTest = "5"

   ' Create the object

   Set objByRefSample = CreateObject("MyObject.ByRefSample")

   ' Call the method

   objByRefSample.PassIntegerByReference (intTest)
   ' Destroy the object
   Set objByRefSample = Nothing

 

The PassIntegerByReference method is a VB sub-procedure with just one argument of type integer that is passed ByRef.

 

What happens is that the value 5 stored in the intTest variable is actually explicitly coerced into a variable of subtype Integer, so that it conforms to the methods argument type. If you remove the parentheses, you will get a runtime error, because the implicit coercion will treat the string value as a double.

 

This is just one way of solving the problem. Another way is to use the CInt conversion function (listed below) when calling the method.

 

At some point however, you might need to convert a value of one data subtype to another data subtype. This can be necessary for various reasons:

 

Yo u need to present a number in hexadecimal notation instead of decimal

You need the corresponding character code for a character or vice versa

You need to pass values to a non-variant property procedure or as a function parameter in a COM object

You need to save data in a database

 

See Chapter 2 Variables, Data Types, and Control of Flow for an explanation of the different data types.

 

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

Top of Page

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 two bytes as opposed to ANSI characters that only need one.

 

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

Top of Page

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

Top of Page

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 non-zero value.

 

See Also

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

Top of Page

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

Top of Page

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

Top of Page

CDate

See under Date & Time functions

 

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

Top of Page

Chr

Returns the ANSI character corresponding to charactercode.

 

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 non-printable 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

Top of Page

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 non-printable ASCII character. This function is used instead of the Chr (returns a two-byte character) function when you only want 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

Top of Page

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 non-printable ASCII character. This function is used instead of the Chr function when you want to return a double byte character. 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

Top of Page

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 or 6, 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

Top of Page

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 or 6, 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

Top of Page

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

Top of Page

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

Top of Page

Fix

See under Mathfunctions

 

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

Top of Page

Int

See under Mathfunctions

 

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

   
Top of Page

 

 

Unsupported conversion functions

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

 

Function Name

Alternative

CVar

Not needed since all conversion to a Variant is implicit.

 

CVDate

CDate, Date

 

Str

CStr

 

Val

CDbl, CInt, CLng and CSng

 

 

   
Top of Page

 


Miscellaneous Functions, Statements and Keywords

Some functionality does not fit under any of the other categories, and so they have gathered them here. Below you will find descriptions of various functions for handling objects, user input, variable checks, output on screen, etc.

 

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 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. Please 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

Top of Page

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, i.e. you need to consider when and where you want to declare your variables. Variables that are only used 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 statement and Set statement

Top of Page

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 is 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 statement

Top of Page

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 is 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
ExecProc's
scope 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 above shown Execute statement in a procedure, the ExecProc procedure will only be accessible within the procedure where the Execute statement is called. You can get around this by simply moving the Execute statement to the script level or using the ExecuteGlobal statement.

 

Example

Dim lngResult
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 statement

Top of Page

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, you must separate them using colons or embedded line breaks.

 

Note

 

Because the assignment operator and the comparison operator is 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 statement

Top of Page

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 criteria.

 

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, i.e. a case sensitive comparison.
vbTextCompare – 1 Performs a textual comparison, i.e. 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 (0) which has the value  Red.

See Also

See the StringFunctionReplace

Top of Page

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. Please 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 above-mentioned problems with ActiveX DLL's 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 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

Top of Page

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 ")

Top of Page

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

Top of Page

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 Variants 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

Top of Page

IsNull

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

 

 

IsNull(expression)

 

expression is any expression.

 

Syntax

 

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

Top of Page

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

Top of Page

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 statement and VarType

Top of Page

LoadPicture

Returns a picture object.

 

Syntax

 

LoadPicture(picturename)

 

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

 

Note

 

This function is only available 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( "")

 

Top of Page

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/she can continue.                                     

 

vbSystemModal             4096                     The same effect as vbApplicationModal. Presumably this is a "left-over" from the good old 16-bit Windows days. The dialog box will stay on top of other windows though.

 

 

Please note how the values are grouped:

 

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 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

Top of Page

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)

Top of Page

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

Top of Page

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

Top of Page

ScriptEngineMajorVersion

Returns the major version number of the script engine being used. The major version number is the part before the decimal separator, e.g. 5 if the version is 5.1.

 

Syntax

 

ScriptEngineMajorVersion

Note

 

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

See Also

ScriptEngine, ScriptEngineBuildVersion and ScriptEngineMinorVersion

Top of Page

ScriptEngineMinorVersion

Returns the minor version number of the script engine being used. The minor version number is the part after the decimal separator, e.g. 1 if the version is 5.1.

 

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 one more references to the same object. Any changes made to the object will be "visible" in to all references.

 

New, is only used 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 only released, 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 no 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 (Chapter 8: Classes in VBScript) and GetRef

Top of Page

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

 

Double         Double-precision floating-point

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

Top of Page

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

   
Top of Page