The Language Reference

The elements of the VBScript language can be broken into four main areas: statements, functions, operators, and object models.

Statements

Statements form the cornerstone of the language. You'll notice in Appendix A that the largest concentration of statements is in the program structure section. Statements are used mainly for such tasks as declaring variables or procedures.

Functions

In general, functions return a value, although, as with any function, you can choose to ignore the return value.

Operators

An operator connects or performs some operation upon one or more language elements to form a single expression. For example, in the code fragment:

strResult = 16 + int(lngVar1)

the addition operator (+) combines 16 and the value returned by int(lngVar1) into a single expression whose value is assigned to the variable strResult. Operators are not documented in this chapter but are listed in Appendix C.

Object models

An integral part of VBScript is the Microsoft Scripting Runtime, which provides an add-on library containing the Dictionary object (which is similar to a Perl associative array) and the FileSystemObject object (which provides access to a local filesystem). Because of their significance, both object models are fully documented in this book.

VBScript is a high-level language and, like all high-level languages, it is a large yet rich language. While this means that it takes time for new users to understand the intricacies of the functions and statements available to them, at the same time, the language's syntax is straightforward, logical, and easy to understand.

To speed the process of finding the right function or statement to perform a particular task, you can use Appendix A to determine what language elements are available for the purpose you require.

Abs Function  

Syntax

result = Abs(number)

number

Use: Required

Data Type: Any valid numeric expression

A number or a string representation of a number.

Return Value

The absolute value of number. The data type is the same as that passed to the function if number is numeric, and Double if it is not.

Description

Returns the absolute value of a number (i.e., its unsigned magnitude). For example, Abs(-1) and Abs(1) both return 1.

Rules at a Glance

  • number can be a number, a string representation of a number, an object whose default property is numeric, or a Null or Empty.
  • If number is Null, the function returns Null.
  • If number is an uninitialized variable or Empty, the function returns zero.

See Also

IsNumeric Function

Array Function  

Syntax

Array([element1], [elementN],....)

element

Use: Optional

Data Type: Any

The data to be assigned to the first array element.

elementN

Use: Optional

Data Type: Any

Any number of data items you wish to add to the array.

Return Value

A variant array consisting of the arguments passed into the function.

Description

Returns a variant array containing the elements whose values are passed to the function as arguments.

The code fragment:

Dim vaMyArray
vaMyArray = Array("Mr", "Mrs", "Miss", "Ms")

is similar to writing:

Dim vaMyArray(3)
vaMyArray(0) = "Mr"
vaMyArray(1) = "Mrs"
vaMyArray(2) = "Miss"
vaMyArray(3) = "Ms"

Because Array creates a variant array, you can pass any data type, including objects, to the Array function. You can also pass the values returned by calls to other Array functions to create multidimensional arrays; these kinds of arrays are called "ragged" arrays.

Rules at a Glance

  • Although the array you create with the Array function is a variant array data type, the individual elements of the array can be a mixture of different data types.
  • The initial size of the array you create is the number of arguments you place in the argument list and pass to the Array function.
  • The lower bound of the array created by the Array function is 0.
  • The array returned by the Array function is a dynamic rather than a static array. Once created, you can redimension the array using Redim, Redim Preserve, or another call to the Array function.
  • If you don't pass any arguments to the Array function, an empty array is created. Although this may appear to be the same as declaring an array in the conventional manner with the statement:

    Dim myArray( )

    the difference is that you can then use the empty array with the Array function again later in your code.

Example

<%
Dim myArray
myArray = Array(100, 2202, 3.3, 605, 512)
Response.Write myArray(2)
%>

Programming Tips and Gotchas

  • The Array function was not present in the first version of VBScript and was added to the language in Version 2.
  • You cannot assign the return value of Array to a variable previously declared as an array variable. Therefore, don't declare the variant variable as an array using the normal syntax:

    Dim MyArray( )

    Instead, simply declare a variant variable, such as:

    Dim MyArray
  • The Array function is ideal for saving space and time and for writing more efficient code when creating a fixed array of known elements, for example:

    Dim Titles
    Title = Array("Mr", "Mrs", "Miss", "Ms")

    You can use the Array function to create multidimensional arrays. However, accessing the elements of the array needs a little more thought. The following code fragment creates a simple two-dimensional array with three elements in the first dimension and four elements in the second:

    Dim vaListOne
     
    vaListOne = Array(Array(1, 2, 3, 4), _
     Array(5, 6, 7, 8), _
     Array(9, 10, 11, 12))

    Surprisingly, the code you'd expect to use to access the array returns a "Subscript out of range" error:

    'This line generates a Subscript out of range error
    Response.Write vaListOne(1, 2)

    Instead, since this is an array stored within an array (that is, a ragged array), you can access it as follows:

    Response.Write vaListOne(1)(2)
  • Because you declare the variant variable to hold the array as a simple variant, rather than an array and can then make repeated calls to Array, the function can create dynamic arrays. For example, the following code fragment dimensions a variant to hold the array, calls Array to create a variant array, then calls Array again to replace the original variant array with a larger variant array:

    Dim varArray
    varArray = Array(10,20,30,40,50)
    ...
    varArray = Array(10,20,30,40,50,60)

    The major disadvantage of using this method is that while it makes it easy to replace an array with a different array, it doesn't allow you to easily expand or contract an existing array.

VBA/VBScript Differences

Unlike Visual Basic, VBScript does not contain an Option Base statement; therefore, arrays created in VBScript using the Array function have a lower boundary of 0. That is, the first element of the array will always be accessed using an index value of 0.

See Also

Dim Statement, LBound Function, ReDim Statement, UCase Function

Asc, AscB, AscW Functions  

Syntax

Asc(string)
AscB(string)
AscW(string)

string

Use: Required

Data Type: String

Any expression that evaluates to a string.

Return Value

An integer that represents the character code of the first character of the string.

Description

Returns the ANSI (in the case of Asc) or Unicode (in the case of AscW ) character code that represents the first character of the string passed to it. All other characters in the string are ignored. The AscB function returns the first byte of a string.

Rules at a Glance

  • The string expression passed to the function must contain at least one character, or a runtime error (either "Invalid use of Null" or "Invalid procedure call or argument") is generated.
  • Only the first character of the string is evaluated by Asc, AscB, and AscW.
  • Use the AscW function to return the Unicode character of the first character of a string.
  • Use the AscB function to return the first byte of a string containing byte data.

Example

<%
Dim sChars
Dim iCharCode
 
sChars = Request.Form("chars")
If Len(sChars) > 0 Then
 CharCode = Asc(sChars)
 If iCharCode >= 97 And iCharCode <= 122 Then
 Response.Write "The first character must be uppercase"
 Else
 Response.Write iCharCode 
 End If
End If
%>

Programming Tips and Gotchas

  • Always check that the string you are passing to the function contains at least one character using the Len function, as the following example shows:

    If Len(sMyString) > 0 Then
     iCharCode = Asc(sMyString)
    Else
     Response.Write "Cannot process a zero-length string"
    End If
  • Surprisingly, although the VBScript documentation shows that the data type of the parameter passed to the Asc function is String, it can actually be any data type. Evidently the Asc routine converts incoming values to strings before extracting their first character. Try this quick example for yourself:

    <%
    sChars = 123
    Response.Write Asc(sChars)
    %>
  • Use Asc within your data validation routines to determine such conditions as whether the first character is upper- or lowercase and whether it's alphabetic or numeric, as the following example demonstrates:

    Function CheckText (sText)
    
    Dim iChar
     
    If Len(sText) > 0 Then
     iChar = Asc(sText)
     If iChar >= 65 And iChar <= 90 Then
     CheckText = "The first character is UPPERCASE"
     ElseIf iChar >= 97 And iChar <= 122 Then
     CheckText = "The first character is lowercase"
     Else
     CheckText = "The first character isn't alphabetical"
     End If
    Else
     CheckText = "Please enter something in the text box"
    End If
     
    End Function

See Also

Chr, ChrB, ChrW Functions

Atn Function  

Syntax

Atn(number)

number

Use: Required

Data Type: Numeric

Any numeric expression, representing the ratio of two sides of a right angle triangle.

Return Value

The return value is a Double representing the arctangent of number in the range -pi/2 to pi/2 radians.

Description

Takes the ratio of two sides of a right triangle (number) and returns the corresponding angle in radians. The ratio is the length of the side opposite the angle divided by the length of the side adjacent to the angle.

Rules at a Glance

  • If no number is specified, a runtime error is generated.
  • The return value of Atn is in radians, not degrees.

Example

<% 
Const Pi = 3.14159
 Dim dblSideAdj, dblSideOpp 
 Dim dblRatio, dblAtangent, dblDegrees

 dblSideAdj = 50.25
 dblSideOpp = 75.5
 
 dblRatio = dblSideOpp / dblSideAdj
 dblAtangent = Atn(dblRatio)
 ' convert from radians to degrees
 dblDegrees = dblAtangent * (180 / Pi)
 Response.Write dblDegrees & " Degrees"
%>

Programming Tips and Gotchas

  • To convert degrees to radians, multiply degrees by pi/180.
  • To convert radians to degrees, multiply radians by 180/pi.
  • Don't confuse Atn with the cotangent. Atn is the inverse trigonometric function of Tan, as opposed to the simple inverse of Tan.

See Also

Tan Function

Call Statement  

Syntax

[Call] procedurename [argumentlist]

Call

Use: Optional

Use: Required

Data Type: n/a

The name of the subroutine being called.

argumentlist

Use: Optional

Data Type: Any

A comma-delimited list of arguments to pass to the subroutine being called.

Description

Passes program control to an explicitly named procedure or function.

Rules at a Glance

  • The Call statement requires that the procedure being called be named explicitly. You cannot assign the subroutine name to a variable and provide that as an argument to the Call statement. For example, the following is an illegal use of Call:

    Dim sProc
    sProc = "PrintRoutine"
    Call sProc(sReport) ' Illegal: sProc is a variable

    The following code fragment shows a valid use of the Call statement:

    Call PrintRoutine(sReport) ' Legal usage
  • You aren't required to use the Call keyword when calling a function procedure. However, if you use the Call keyword to call a procedure that requires arguments, argumentlist must be enclosed in parentheses. If you omit the Call keyword from the procedure call, you must also omit the parentheses around argumentlist.

Example

The WSH code fragment shows a call to a procedure that passes two arguments: a string array and a string. Note that while the call to the ShowList procedure uses the Call keyword, the equivalent call to the MsgBox function within the ShowList procedure does not:

Dim aList, sCaption

aList = Array("One", "Two", "Three", "Four")
sCaption = "Array Contents"
Call ShowList(aList, sCaption) 

Sub ShowList(arr( ), s2)
 Dim mem, sMsg

 For Each mem In arr
 sMsg = sMsg & mem & vbCrLf
 Next

 MsgBox sMsg, ,s2
End Sub

Programming Tips and Gotchas

  • You can use the Call keyword to call a function when you're not interested in the function's return value.
  • The use of the Call keyword is considered outdated. We suggest not using the keyword, as it is unnecessary and provides no value.
  • If you remove the Call statement but fail to remove the parentheses from a call to a subroutine with a single argument, then that argument is passed by value rather than by reference. This can have unintended consequences.

VBA/VBScript Differences

VBA (as of Version 6.0) supports the CallByName function, which allows you to call a public procedure in a VBA object module by assigning the procedure name to a variable. VBScript does not support the CallByName function and requires that you provide the name of the function or sub procedure in the Call statement.

CBool Function  

Syntax

CBool(expression)

expression

Use: Required

Data Type: String or Numeric

Any numeric expression or a string representation of a numeric value.

Return Value

expression converted to a type of Boolean (True or False).

Description

Casts expression as aa Boolean type. Expressions that evaluate to 0 are converted to False (0), and expressions that evaluate to nonzero values are converted to True (-1).

Rules at a Glance

If the expression to be converted is a string, the string must act as a number. Therefore, CBool("ONE") results in a type mismatch error, yet CBool("1") converts to True.

Programming Tips and Gotchas

  • You can check the validity of the expression prior to using the CBool function by using the IsNumeric function.
  • When you convert an expression to a Boolean, an expression that evaluates to 0 is converted to False (0), and any nonzero number is converted to True (-1). Therefore, a Boolean False can be converted back to its original value (i.e., 0), but the original value of the True expression can't be restored unless it was originally -1.

See Also

IsNumeric Function

CByte Function  

Syntax

CByte(expression)

expression

Use: Required

Data Type: Numeric or String

A string or numeric expression that evaluates between 0 and 255.

Return Value

expression converted to a type of Byte.

Description

Converts expression to a Byte data type. The Byte type is the smallest data storage device in VBScript. Being only one byte in length, it can store unsigned numbers between 0 and 255.

Rules at a Glance

  • If expression is a string, the string must be capable of being treated as a number.
  • If expression evaluates to less than 0 or more than 255, an overflow error is generated.
  • If expression isn't a whole number, CByte rounds the number prior to conversion.

Example

If IsNumeric(sMyNumber) Then
 If val(sMyNumber) >= 0 and val(sMyNumber) <= 255 Then
 BytMyNumber = Cbyte(sMyNumber)
 End If
End If

Programming Tips and Gotchas

  • Check that the value you pass to CByte is neither negative nor greater than 255.
  • Use IsNumeric to insure the value passed to CByte can be converted to a numeric expression.
  • When using CByte to convert floating-point numbers, fractional values up to but not including 0.5 are rounded down, while values greater than 0.5 are rounded up. Values of 0.5 are rounded to the nearest even number (i.e., they use the Banker's Rounding Algorithm).

See Also

IsNumeric Function

CCur Function  

Syntax

CCur(expression)

expression

Use: Required

Data Type: Numeric or String

A string or numeric expression that evaluates to a number between -922,337,203,685,477.5808 and 922,337,203,685,477.5807.

Return Value

expression converted to a type of Currency.

Description

Converts an expression into a type of Currency.

Rules at a Glance

  • If the expression passed to the function is outside the range of the Currency data type, an overflow error occurs.
  • Expressions containing more than four decimal places are rounded to four decimal places.
  • The only localized information included in the value returned by CCur is the decimal symbol.

Example

If IsNumeric(sMyNumber) Then
 curMyNumber = CCur(sMyNumber)
End If

Programming Tips and Gotchas

  • CCur doesn't prepend or append a currency symbol; for this, you need to use the FormatCurrency function. CCur does, however, correctly convert strings that include a localized currency symbol. For instance, if a user enters the string "$1234.68" into a text box whose value is passed as a parameter to the CCur function, CCur correctly returns a currency value of 1234.68.
  • CCur doesn't include the thousands separator; for this, you need to use the FormatCurrency function. CCur does, however, correctly convert currency strings that include localized thousands separators. For instance, if a user enters the string "1,234.68" into a text box whose value is passed as a parameter to the CCur function, CCur correctly converts it to a currency value of 1234.68.

See Also

FormatCurrency, FormatNumber, FormatPercent Functions

CDate Function  

Syntax

CDate(expression)

expression

Use: Required

Data Type: String or Numeric

Any valid date expression.

Return Value

expression converted into a Date type.

Description

Converts expression to a Date type. The format of expressionthe order of day, month, and yearis determined by the locale setting of your computer. To be certain of a date being recognized correctly by CDate, the month, day, and year elements of expression must be in the same sequence as your computer's regional settings; otherwise, the CDate function has no idea that in the expression "04/01/01," 4 is supposed to be the 4th of the month, not the month of April, for example.

CDate also converts numbers to a date. The precise behavior of the function, however, depends on the value of expression :

  • If expression is less than or equal to 23 and includes a fractional component less than 60, the integer is interpreted as the number of hours since midnight, and the fraction is interpreted as the number of seconds.
  • In all other cases, the integer portion of expression is converted to a date that interprets the integer as the number of days before (in the case of negative numbers) or after December 31, 1899, and its fractional part is converted to the time of day, with every .01 representing 864 seconds (14 minutes 24 seconds) after midnight.

Rules at a Glance

  • CDate accepts both numerical date expressions and string literals. You can pass month names into CDate in either complete or abbreviated form; for example, "31 Dec 1997" is correctly recognized.
  • You can use any of the date delimiters specified in your computer's regional settings; for most systems, this includes , / - and the space character.
  • The oldest date that can be handled by the Date data type is 01/01/100, which in VBScript terms equates to the number -657434. Therefore, if you try to convert a number of magnitude greater than -657434 with CDate, an error ("Type mismatch") is generated.
  • The furthest date into the future that can be handled by the Date data type is 31/12/9999, which in VBScript terms equates to the number 2958465. Therefore, if you try to convert a number higher than 2958465 with CDate, an error ("Type mismatch") is generated.
  • A "Type mismatch" error is generated if the values supplied in expresssion are invalid. CDate tries to treat a month value greater than 12 as a day value.

Programming Tips and Gotchas

  • Use the IsDate function to determine if expression can be converted to a date or time.
  • A common error is to pass an uninitialized variable to CDate, in which case midnight will be returned
  • A modicum of intelligence has been built into the CDate function. It can determine the day and month from a string regardless of their position, but only where the day number is larger than 12, which automatically distinguishes it from the number of the month. For example, if the string "30/12/97" were passed into the CDate function on a system expecting a date format of mm/dd/yy, CDate sees that 30 is obviously too large for a month number and treats it as the day. It's patently impossible for CDate to second guess what you mean by "12/5/97"is it the 12th of May, or 5th of December? In this situation, CDate relies on the regional settings of the computer to distinguish between day and month. This can also lead to problems, as you may have increased a month value to more than 12 inadvertently in an earlier routine, thereby forcing CDate to treat it as the day value. If your real day value is 12 or less, no error is generated, and a valid, albeit incorrect, date is returned.
  • If you pass a two-digit year into CDate, how does it know which century you are referring to? Is "10/20/97" 20 October 1997 or 20 October 2097? The answer is that two-year digits less than 30 are treated as being in the 21st Century (i.e., 29 = 2029), and two-year digits of 30 and over are treated as being in the 20th Century (i.e., 30 = 1930).
  • Don't follow a day number with "st," "nd," "rd," or "th," since this generates a type mismatch error.
  • If you don't specify a year, the CDate function uses the year from the current date on your computer.

VBA/VBScript Differences

If you pass an initialized variable to the CDate function in VBA, the return value is 31 December 1899. In VBScript, the function's return value is 12:00:00 AM.

See Also

FormatDateTime Function

CDbl Function  

Syntax

CDbl(expression)

expression

Use: Required

Data Type: Numeric or String

-1.79769313486232E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values.

Return Value

expression cast as a Double type.

Description

Converts expression to a Double type.

Rules at a Glance

  • If the value of expression is outside the range of the double data type, an overflow error is generated.
  • Expression must evaluate to a numeric value; otherwise, a type mismatch error is generated.

Example

Dim dblMyNumber as Double
If IsNumeric(sMyNumber) then
 dblMyNumber = CDbl(sMyNumber)
End If

Programming Tips and Gotchas

Use IsNumeric to test whether expression evaluates to a number.

See Also

IsNumeric Function

Chr, ChrB, ChrW Functions  

Syntax

Chr(charactercode)
ChrB(charactercode)
ChrW(charactercode)

charactercode

Use: Required

Data Type: Long

An expression that evaluates to either an ANSI or Unicode character code.

Return Value

Chr, ChrB, and ChrW return a variant of the string type that contains the character represented by charactercode.

Description

Returns the character represented by charactercode.

Rules at a Glance

  • Chr returns the character associated with an ANSI character code.
  • ChrB returns a one-byte string.
  • ChrW returns a Unicode character.

Programming Tips and Gotchas

  • Use Chr(34) to embed quotation marks inside a string, as shown in the following example:
sSQL = "SELECT * from myTable where myColumn = " & Chr(34) & _
 sValue & Chr(34)
  • You can use the ChrB function to assign binary values to String variables.
  • The following table lists some of the more commonly used character codes that are supplied in the call to the Chr function:

Code

Value

Description

0

NULL

For C/C++ string functions, the null character required to terminate standard strings; equivalent to the vbNullChar constant.

9

TAB

Equivalent to the vbTab constant.

10

LF

Equivalent to the vbLf constant.

13

CR

Equivalent to the vbCr constant.

13 & 10

CRLF

Equivalent to the CWlocal constant.

34

"

Quotation mark. Useful to embed quotation marks within a literal string, especially when forming SQL query strings.

See Also

Asc, AscB, AscW Functions, CStr Function


 

Programming Tips and Gotchas

  • Use IsNumeric to test whether expression evaluates to a number before performing the conversion.
  • CInt differs from the Fix and Int functions, which truncate, rather than round, the fractional part of a number. Also, Fix and Int always return a value of the same type as was passed in.
  • In client-side scripts, CInt is useful in converting the string in an HTML intrinsic text box control to a number. This is illustrated in the example.

See Also

CLng Function, Fix Function, FormatCurrency, FormatNumber, FormatPercent Functions, Int Function, IsNumeric Function

CInt Function  

Syntax

CInt(expression)

expression

Use: Required

Data Type: Numeric or String

The range of expression is -32,768 to 32,767; fractions are rounded.

Return Value

expression cast as an integer type.

Description

Converts expression to a type of integer; any fractional portion of expression is rounded.

Rules at a Glance

  • expression must evaluate to a numeric value; otherwise, a type mismatch error is generated.
  • If the value of expression is outside the range of the Integer data type, an overflow error is generated.
  • When the fractional part of expression is exactly 0.5, CInt always rounds to the nearest even number. For example, 0.5 rounds to 0, and 1.5 rounds to 2.

Example


 
Class Statement  

Syntax

Class name
 'statements
End Class

name

Use: Required

Data Type: n/a

The name of the class

Description

Defines a class and delimits the statements that define that class's member variables, properties, and methods.

Rules at a Glance

  • name follows standard Visual Basic variable naming conventions.
  • statements can consist of the following:

    • Private variable definitions. These variables are accessible within the class but not outside it.
    • Public variable definitions. (If variables are declared using the Dim keyword without an explicit indication of their accessibility, they are Public by default.) These variables become public properties of the class.
    • Public functions and subroutines defined with the Function...End Function or Sub...End Sub statements. The scope of routines not explicitly defined by the Public or Private keywords is public by default. These routines become the public methods of the class.
    • Private function and subroutines defined with the Function...End Function or Sub...End Sub statements. They are visible within the Class...End Class code block, but not to code outside the class.
    • Public properties defined using the Property Let, Property Get, and Property Set statements. Properties defined without an explicit Public or Private statement are also Public by default. They, along with any public variables, form the public properties of the class.
    • Private properties defined using the Property Let, Property Get, and Property Set statements. They are visible within the class, but inaccessible outside of it.
  • The default member of the class can be defined by specifying the Default keyword in the member's Function, Sub, or Property Get statement.
  • The Initialize event is fired and the Class_Initialize event procedure is executed, if it is present, when the class is instantiated.
  • The Terminate event is fired and the Class_Terminate event procedure is executed, if it is present, when an instance of the class is destroyed. This occurs when the last variable or property holding the object reference is set to Nothing or when it goes out of scope. Note that, even if all the variables are destroyed, there are situations (such as circular references) in which the object persists until the script engine is destroyed. Hence, the Terminate event procedure may not be called until very late.
  • The class can be instantiated by using the Set statement with the New keyword. For example, if a class named CObject is defined with the Class...End Class construct, the following code fragment instantiates an object belonging to the class:

    Dim oObj
    Set oObj = New CObject

Example

The example defines a class, CCounter, with one read-only property, Value, and one method, ShowCount, as well as an Initialize event procedure and one private variable:

Dim oCtr
Set oCtr = New CCounter

oCtr.Increment
oCtr.Increment
MsgBox "Count: " & oCtr.ShowCount

' definition of CCounter class
Class CCounter
 Private lCtr 

 Private Sub Class_Initialize( )
 lCtr = 1
 End Sub

 Public Sub Increment( )
 lCtr = lCtr + 1
 End Sub

 Public Function ShowCount( )
 ShowCount = Me.Value
 End Function
End Class

Programming Tips and Gotchas

  • A property defined as a simple public variable cannot be designated as the class's default member.
  • Public properties should be defined using the Property Let, Property Get, and Property Set statements, since they allow the value of a property to be modified in a controlled and predictable way. Defining a public variable that becomes accessible outside of the class (that is, defining a variable using either the Dim or Public keywords) is considered poor programming practice.
  • The Me Keyword can be used within the Class...End Class construct to reference the object instance.
  • The Initialize event procedure can be used to initialize variables and property values.
  • The Terminate event procedure can be used to perform cleanup, such as releasing references to child objects, or closing database connections or recordsets. But be very careful about what code you run in the Terminate event terminator. Any code that results in the object being referenced again results in the terminated object's continued existence.
  • A VBScript object instance should never be stored to the Session object in an ASP application. Since VBScript object instances are apartment-threaded, this has the effect of locking down the application to a single thread of execution.

VBA/VBScript Differences

The Class...End Class construct, which is the scripted equivalent of VBA class modules, is not supported in VBA.

See Also

Dim Statement, Function Statement, Initialize Event, Private Statement, Property Get Statement, Property Let Statement, Property Set Statement, Public Statement, Set Statement, Sub Statement, Terminate Event


 

Programming Tips and Gotchas

  • Use IsNumeric to test whether expression evaluates to a number.
  • CLng differs from the Fix and Int functions, which truncate, rather than round, the fractional part of a number. Also, Fix and Int always return a value of the same type as was passed in.
  • In client-side scripts, CLng is useful in converting the string in an HTML intrinsic text box control to a number. This is illustrated in the example.

See Also

CInt Function, Fix Function, FormatCurrency, FormatNumber, FormatPercent Functions, Int Function, IsNumeric Function

CLng Function  

Syntax

CLng(expression)

expression

Use: Required

Data Type: Numeric or String

The range of expression is -2,147,483,648 to 2,147,483,647; fractions are rounded.

Return Value

expression cast as a type of Long.

Description

Converts expression to a type of Long; any fractional element of expression is rounded.

Rules at a Glance

  • expression must evaluate to a numeric value; otherwise, a type mismatch error is generated.
  • If the value of expression is outside the range of the long data type, an overflow error is generated.
  • When the fractional part is exactly 0.5, CLng always rounds it to the nearest even number. For example, 0.5 rounds to 0, and 1.5 rounds to 2.

Example


 
Const Statement  

Syntax

[Public|Private] Const constantname = constantvalue

constantname

Use: Required

The name of the constant.

constantvalue

Use: Required

Data Type: Numeric or String

A constant value, and optionally, the + and - unary operators. Unlike variables, constants must be initialized.

Description

Declares a constant value; i.e., its value can't be changed throughout the life of the program or routine. One of the ideas of declaring constants is to make code easier to both write and read; it allows you to replace a value with a recognizable word.

Rules at a Glance

  • The rules for constantname are the same as those of any variable: the name can be up to 255 characters in length and can contain any alphanumeric character or an underscore, although it must start with an alphabetic character. As is the case with variable names, these rules can be overridden by placing brackets around the constant name.
  • constantvalue can be a string or numeric literal. It can be only a single value (a simple constant); that is, it cannot be an expression that includes a call to an intrinsic or user-defined function, property, or method, nor can it contain any arithmetic or string operators or variables. In addition, a constant can't be defined in terms of another constant, as in the statement:

    Public Const CDATE = CSTART_DATE ' Invalid

Example

Private Const my_Constant = 3.1417

Programming Tips and Gotchas

  • The recommended coding convention for constants is the same as variables: use camel casing. This places the first letter of the first word in lowercase, and the first letter of subsequent words in uppercase. All other characters are in lowercase. To improve readability, you can also use underscores to separate words. For example, myConstant or my_Constant are constant names that adhere to this coding convention.
  • One of the benefits of long variable and constant names (of up to 255 characters) in VBScript is that you can make your constant names as meaningful as possible while using abbreviations sparingly. After all, you may know what abbreviations mean, but will others?
  • Rather than having to explicitly define constants found in type libraries, you can access the type library definitions from Windows Script Hosts by using the XML element in an .wsf file (for details, see Chapter 7), and from Active Server Pages by using the tag in the application's global.asa file.

VBA/VBScript Differences

  • VBA allows you to explicitly define the data type of the constant. VBScript, since it does not support strong typing, does not.
  • VBA supports complexconstants; that is, VBA allows you to define constants using other constants, as well as using expressions containing absolute values, operators, and constants. In contrast, VBScript supports only simple constants; that is, it allows you to define a constant using only an absolute value.

See Also

Private Statement, Public Statement

Cos Function  

Syntax

Cos(number)

number

Use: Required

Data Type: Numeric expression

An angle in radians.

Return Value

A type of Double denoting the cosine of an angle.

Description

Takes an angle specified in radians and returns a ratio representing the length of the side adjacent to the angle divided by the length of the hypotenuse.

Rules at a Glance

The cosine returned by the function is between -1 and 1.

Example

Dim dblCosine as Double
dblCosine = Cos(dblRadians)

Programming Tips and Gotchas

  • To convert degrees to radians, multiply degrees by pi/180.
  • To convert radians to degrees, multiply radians by 180/pi.

See Also

Atn Function, Sin Function, Tan Function

CreateObject Function  

Syntax

CreateObject(servername, progID [, location])

servername

Use: Required

Data Type: String

The name of application providing the object.

ProgID

Use: Required

Data Type: String

The programmatic identifier (ProgID) of the object to create, as defined in the system registry.

Location

Use: Optional

Data Type: String

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

Return Value

A reference to an ActiveX object.

Description

Creates an instance of an OLE Automation (ActiveX) object. Prior to calling the methods, functions, or properties of an object, you are required to create an instance of that object. Once an object is created, you reference it in code using the object variable you defined.

Rules at a Glance

  • In order to assign the object reference to a variable, you must use the Set keyword. For example:

    Dim oDoc
    Set oDoc = CreateObject("Word.Document")
  • Programmatic identifiers use a string to identify a particular COM component or COM-enabled application. They are included among the subkeys of HKEY_CLASSES_ROOT in the system registry.
  • Some common programmatic identifiers are shown in the following table:

ProgID

Description

ADODB.Connection

An ActiveX Data Objects connection

ADODB.Recordset

An ActiveX Data Objects recordset

DAO.DBEngine

Data Access Objects

Excel.Application

Microsoft Excel

Excel.Chart

A Microsoft Excel chart

Excel.Sheet

A Microsoft Excel workbook

MAPI.Session

Collaborative Data Objects

Outlook.Application

Microsoft Outlook

Scripting.Dictionary

Dictionary object

Scripting.FileSystemObject

File System object model

Word.Application

Microsoft Word

Word.Document

A Microsoft Word document

  • If an instance of the ActiveX object is already running, CreateObject may start a new instance when it creates an object of the required type.

Example

The following WSH example places text in the first cell of an Excel spreadsheet document, changes the font to bold, saves the document to the MyDocuments folder, and closes the Excel application. In this example, Excel must already be running for the code to work (the code uses the CreateObject function to create a new workbook, but not to open Excel itself), but you can just as easily use the CreateObject function to open an application:

' Get MyDocuments folder
Dim oShell
Dim docfolder
Set oShell = WScript.CreateObject ("WScript.Shell")
docfFolder = oShell.SpecialFolders ("MyDocuments")

'Create and save Excel worksheet
Dim XLObj, XLBook, XLSheet
Set XLObj = CreateObject ("Excel.Application")
XLObj.Application.Visible = True
XLObj. Workbooks.Add( )
Set XLSheet = XLObj.ActiveSheet
XLSheet.Cells(1,1) = "Insert Text Here"
XLSheet.Cells(1,1).Font.Bold = True
XLSheet.SaveAs docFolder & "Test.xls"
XLObj.Application.Quit

Programming Tips and Gotchas

  • In a scripted environment, it's sometimes preferable to use the host application's object model to instantiate new objects rather than to use the VBScript CreateObject function. For instance, using the CreateObject method of the IIS Server object instead of the VBScript CreateObject function allows ASP to track the object instance and allows the object to participate in MTS or COM+ transactions. In Windows Script Host, using the CreateObject method of the WScript object instead of the VBScript CreateObject function allows WSH to track the object instance and to handle the object's events. When using VBScript to develop an Outlook form, the CreateObject method of the Application object is the preferred way to instantiate an external class.
  • The CreateObject function does not succeed in client-side Internet Explorer scripts if the code attempts to create a dangerous object or the user's security policy does not allow it. In order to instantiate an object, use the HTML tag.
  • VBScript offers the ability to reference an object on another network server. Using the Location parameter, you can pass in the name of a remote server and the object can be referenced from that server. This means that you could even specify different servers depending upon prevailing circumstances, as this short example demonstrates:

    Dim sMainServe
    Dim sBackUpServer
    
    sMainServer = "NTPROD1"
    sBackUpServer = "NTPROD2"
    
    If IsOnline(sMainServer) Then
     CreateObject("Sales.Customer",sMainServer)
    Else
     CreateObject("Sales.Customer",sBackUpServer)
    End If
  • To use a current instance of an already running ActiveX object, use the GetObject function.
  • If an object is registered as a single-instance object (i.e., an out-of-process ActiveX EXE), only one instance of the object can be created; regardless of the number of times CreateObject is executed, you will obtain a reference to the same instance of the object.
  • An urban programming legend says it's necessary to release unused object references by setting them to Nothing when the reference is no longer needed. But since unused object references are released when they go out of scope, this step is not necessary. In general, object variables need to be explicitly released only to free circular references.
  • Using the CreateObject function's location parameter to invoke an object remotely requires that the object be DCOM-aware. As an alternative, scripts can be run remotely using Remote Windows Script Host, a technology briefly discussed in Chapter 7.
  • A apartment-threaded COM object instantiated using the CreateObject function should never be stored to the Session object in an ASP application, since doing so locks down the ASP application to a single thread of execution.

VBA/VBScript Differences

  • In VBA, the CreateObject function is just one of the language constructs that you can use to instantiate a new object; you can also use the New keyword in either the object variable declaration or the object assignment. Because VBScript supports only late binding, however, CreateObject (along with a similar method in the target object model that you're using) is the only method available to instantiate objects that are external to the script.
  • While CreateObject under VBA is an intrinsic part of the language, you cannot assume that CreateObject is necessarily available in a particular scripted environment. In Internet Explorer, for instance, calls to the CreateObject method generate a runtime error.

See Also

GetObject Function, Set Statement

CSng Function  

Syntax

CSng(expression)

expression

Use: Required

Data Type: Numeric or String

The range of expression is -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values.

Return Value

expression cast as a type of Single.

Description

Returns a single-precision number.

Rules at a Glance

  • expression must evaluate to a numeric value; otherwise, a type mismatch error is generated.
  • If the value of expression is outside the range of the Single data type, an overflow error is generated.

Example

Dim sngMyNumber
If IsNumeric(sMyNumber) then
 sngMyNumber = CSng(sMyNumber)
End If

Programming Tips and Gotchas

  • If you need to use a floating-point number in VBScript, there is no reason to use a Single; use a Double instead. Generally, a Single is used because it offers better performance than a Double, but this is not true in VBScript. Not only is a Single not smaller than a Double in the VBScript implementation, but the processor also converts Singles to Doubles, performs any numeric operations, and then converts Doubles back to Singles.
  • Test that expression evaluates to a number by using the IsNumeric function.

See Also

FormatCurrency, FormatNumber, FormatPercent Functions, IsNumeric Function

CStr Function  

Syntax

CStr(expression)

expression

Use: Required

Data Type: Any

Any expression that is to be converted to a string.

Return Value

expression converted to a String.

Description

Returns a string representation of expression.

Rules at a Glance

Almost any data can be passed to CStr to be converted to a string.

Example

Dim sMyString
SMyString = CStr(100)

Programming Tips and Gotchas

  • The string representation of Boolean values is either True or False, as opposed to their underlying values of 0 and -1.
  • An uninitialized variable passed to CStr returns an empty string.
  • An object reference cannot be passed to the CStr function. Attempting to do so generates a runtime error.
Date Function  

Syntax

Date

Return Value

Date returns a Date.

Description

Returns the current system date.

Rules at a Glance

They don't come any easier than this!

Programming Tips and Gotchas

To return both the current date and time in one variable, use the Now function.

See Also

IsDate Function, Now Function

DateAdd Function  

Syntax

DateAdd(interval, number, date)

interval

Use: Required

Data Type: String

An expression denoting the interval of time you need to add or subtract (see the following table "Interval Settings").

number

Use: Required

Data Type: Any numeric type

An expression denoting the number of time intervals you want to add or subtract.

date

Use: Required

Data Type: Date

The date on which to base the DateAdd calculation.

Interval Settings

Setting

Description

yyyy

Year

q

Quarter

m

Month

y

Day of year

d

Day

w

Weekday

ww

Week

h

Hour

n

Minute

s

Second

Return Value

A Date.

Description

Returns a Date representing the result of adding or subtracting a given number of time periods to or from a given date or time. For instance, you can calculate the date 178 months before today's date, or the date and time 12,789 minutes from now.

Rules at a Glance

  • Specify the interval value as a string enclosed in quotation marks (e.g., "ww").
  • If number is positive, the result will be after date; if number is negative, the result will be before date.
  • The DateAdd function has a built-in calendar algorithm to prevent it from returning an invalid date. For example, if you add 10 minutes to 31 December 1999 23:55, DateAdd automatically recalculates all elements of the date to return a valid datein this case, 1 January 2000 00:05. In addition, the calendar algorithm takes the presence of 29 February into account for leap years.

Example

Dim lNoOfIntervals
lNoOfIntervals = 100
Msgbox DateAdd("d", lNoOfIntervals, Now)

Programming Tips and Gotchas

  • When working with dates, always check that a date is valid using the IsDate function prior to passing it as a parameter to the function.
  • To add a number of days to date, use either the day of the year "y", the day "d", or the weekday "w".
  • The Variant date type can handle only dates as far back as 100 A.D. DateAdd generates an error (runtime error number 5, "Invalid procedure call or argument") if the result precedes the year 100.
  • The Variant date type can handle dates as far into the future as 9999 A.D.from a practical application standpoint, a virtual infinity. If the result of DateAdd is a year beyond 9999 A.D., the function generates runtime error number 5, "Invalid procedure call or argument."
  • If number contains a fractional value, it's rounded to the nearest whole number before being used in the calculation.

See Also

DateDiff Function, DatePart Function, DateSerial Function, IsDate Function

DateDiff Function  

Syntax

DateDiff(interval, date1, date2[, firstdayofweek[, firstweekofyear]])

interval

Use: Required

Data Type: String

The units of time used to express the result of the difference between date1 and date2 (see the following "Interval Settings" table).

date1

Use: Required

Data Type: Date

The first date you want to use in the differential calculation.

date2

Use: Required

Data Type: Date

The second date you want to use in the differential calculation.

firstdayofweek

Use: Optional

Data Type: Integer

A numeric constant that defines the first day of the week. If not specified, Sunday is assumed (see the following table "First Day of Week Constants").

firstweekofyear

Use: Optional

Data Type: Integer

A numeric constant that defines the first week of the year. If not specified, the first week is assumed to be the week in which January 1 occurs (see the following table "First Week of Year Constants").

Interval Settings

Setting

Description

yyyy

Year

q

Quarter

m

Month

y

Day of year

d

Day

w

Weekday

ww

Week

h

Hour

n

Minute

s

Second

First Day of Week Constants

Constant

Value

Description

vbUseSystem

0

Use the NLS API setting

vbSunday

1

Sunday (default)

vbMonday

2

Monday

vbTuesday

3

Tuesday

vbWednesday

4

Wednesday

vbThursday

5

Thursday

vbFriday

6

Friday

vbSaturday

7

Saturday

First Week of Year Constants

Constant

Value

Description

vbUseSystem

0

Use the NLS API setting

vbFirstJan1

1

Start with the week in which January 1 occurs (default)

vbFirstFourDays

2

Start with the first week that has at least four days in the new year

vbFirstFullWeek

3

Start with first full week of the year

Return Value

A Long specifying the number of time intervals between two dates.

Description

The DateDiff function calculates the number of time intervals between two dates. For example, you can use the function to determine how many days there are between 1 January 1980 and 31 May 1998.

Rules at a Glance

  • The calculation performed by DateDiff is always date2-- date1. Therefore, if date1 chronologically follows date2, the value returned by the function is negative.
  • If interval is Weekday "w", DateDiff returns the number of weeks between date1 and date2. DateDiff totals the occurrences of the day on which date1 falls, up to and including date2, but not including date1. Note that an interval of "w" doesn't return the number of weekdays between two dates, as you might expect.
  • If interval is Week "ww", DateDiff returns the number of calendar weeks between date1 and date2. To achieve this, DateDiff counts the number of Sundays (or whichever other day is defined to be the first day of the week by the firstdayofweek argument) between date1 and date2. date2 is counted if it falls on a Sunday, but date1 isn't counted, even if it falls on a Sunday.
  • The firstdayofweek argument affects only calculations that use the "ww" (week) interval values.

Example

Dim dtNow, dtThen
Dim sInterval
Dim lNoOfIntervals

dtNow = Date
dtThen = #01/01/1990#
sInterval = "m"

lNoOfIntervals = DateDiff(sInterval, dtThen, dtNow)

MsgBox lNoOfIntervals

Programming Tips and Gotchas

  • When working with dates, always check that a date is valid using the IsDate function prior to passing it as a function parameter.
  • When comparing the number of years between December 31 of one year and January 1 of the following year, DateDiff returns 1, although in reality, the difference is only one day.
  • DateDiff considers the four quarters of the year to be January 1-March 31, April 1-June 30, July 1-September 30, and October 1-December 31. Consequently, when determining the number of quarters between March 31 and April 1 of the same year, for example, DateDiff returns 1, even though the latter date is only one day after the former.
  • If interval is "m", DateDiff simply counts the difference in the months on which the respective dates fall. For example, when determining the number of months between January 31 and February 1 of the same year, DateDiff returns 1, even though the latter date is only one day after the former.
  • To calculate the number of days between date1 and date2, you can use either Day of year "y" or Day "d".
  • In calculating the number of hours, minutes, or seconds between two dates, if an explicit time isn't specified, DateDiff provides a default value of midnight (00:00:00).
  • If you specify date1 or date2 as strings within quotation marks (" ") and omit the year, the year is assumed to be the current year, as taken from the computer's date. This allows the same code to be used in different years.

See Also

DateAdd Function, DatePart Function, IsDate Function

DatePart Function  

Syntax

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

interval

Use: Required

Data Type: String

The unit of time to extract from within date (see the following table "Interval Settings").

date

Use: Required

Data Type: Date

The Date value that you want to evaluate.

firstdayofweek

Use: Optional

Data Type: Integer

A numeric constant that defines the first day of the week. If not specified, Sunday is assumed (see the following table "First Day of Week Constants").

firstweekofyear

Use: Optional

Data Type: Integer

A numeric constant that defines the first week of the year. If not specified, the first week is assumed to be the week in which January 1 occurs (see the following table "First Week of Year Constants").

Interval Settings

Setting

Description

yyyy

Year

q

Quarter

m

Month

y

Day of year

d

Day

w

Weekday

ww

Week

h

Hour

n

Minute

s

Second

First Day of Week Constants

Constant

Value

Description

vbUseSystem

0

Use the NLS API setting

vbSunday

1

Sunday (default)

vbMonday

2

Monday

vbTuesday

3

Tuesday

vbWednesday

4

Wednesday

vbThursday

5

Thursday

vbFriday

6

Friday

vbSaturday

7

Saturday

First Week of Year Constants

Constant

Value

Description

vbUseSystem

0

Use the NLS API setting

vbFirstJan1

1

Start with week in which January 1 occurs (default)

vbFirstFourDays

2

Start with the first week that has at least four days in the new year

vbFirstFullWeek

3

Start with first full week of the year

Return Value

An Integer.

Description

Extracts an individual component of the date or time (like the month or the second) from a date/time value. It returns an Integer containing the specified portion of the given date. DatePart is a single function encapsulating the individual Year, Month, Day, Hour, Minute, and Second functions.

Rules at a Glance

  • The firstdayofweek argument affects only calculations that use either the "w" or "ww" interval values.
  • The firstdayofweek argument affects only calculations that use the "ww" interval value.

Example

Dim sTimeInterval
Dim dtNow
 
sTimeInterval = "n" 'minutes
dtNow = Now
 
MsgBox DatePart(sTimeInterval, dtNow)

Programming Tips and Gotchas

  • When working with dates, always check that a date is valid using the IsDate function prior to passing it as a function parameter.
  • If you specify date within quotation marks (" ") omitting the year, the year is assumed to be the current year taken from the computer's date.
  • If you attempt to extract either the hours, the minutes, or the seconds, but date1 doesn't contain the necessary time element, the function assumes a time of midnight (0:00:00).

See Also

DateSerial Function, Day Function, Month Function, Year Function, Minute Function, Hour Function, Second Function

DateSerial Function  

Syntax

DateSerial(year, month, day)

year

Use: Required

Data Type: Integer

Number between 0 and 9999, inclusive.

month

Use: Required

Data Type: Integer

Any numeric expression to express the month between 1 and 12.

day

Use: Required

Data Type: Integer

Any numeric expression to express the day between 1 and 31.

Return Value

A Date.

Description

Returns a Date from the three date components (year, month, and day). For the function to succeed, all three components must be present and all must be numeric values.

Rules at a Glance

  • If the value of a particular element exceeds its normal limits, DateSerial adjusts the date accordingly. For example, if you tried DateSerial (96,2,31)February 31, 1996DateSerial returns March 2, 1996.
  • You can specify expressions or formulas that evaluate to individual date components as parameters to DateSerial. For example, DateSerial (98,10+9,23) returns 23 March 1999. This makes it easier to use DateSerial to form dates whose individual elements are unknown at design time or that are created on the fly as a result of user input.

Example

Dim iYear, iMonth, iday

iYear = 1987
iMonth = 3 + 11
iday = 16

MsgBox DateSerial(iYear, iMonth, iday)

Programming Tips and Gotchas

  • If any of the parameters exceed the range of the Integer data type (-32,768 to 32,767), an error (runtime error 6, "Overflow") is generated.
  • The Microsoft documentation for this function incorrectly states, "For the year argument, values between 0 and 99, inclusive, are interpreted as the years 1900-1999." In fact, DateSerial handles two-digit years in the same way as other Visual Basic date functions. A year argument between 0 and 29 is taken to be in the 21st Century (2000 to 2029); year arguments between 30 and 99 are taken to be in the 20th Century (1930 to 1999). Of course, the safest way to specify a year is to use the full four digits.

See Also

DateAdd Function

DateValue Function  

Syntax

DateValue(stringexpression)

stringexpression

Use: Required

Data Type: String expression

Any of the date formats recognized by IsDate.

Return Value

Variant of type Date.

Description

Returns a Date variant containing the date represented by stringexpression. DateValue can successfully recognize a stringexpression in any of the date formats recognized by IsDate. DateValue doesn't return time values in a date/time string; they are simply dropped. However, if stringexpression includes a valid date value but an invalid time value, a runtime error results.

Rules at a Glance

  • The order of the day, the month, and the year within stringexpression must be the same as the sequence defined by the computer's regional settings.
  • Only those date separators recognized by IsDate can be used.
  • If you don't specify a year in your date expression, DateValue uses the current year from the computer's system date.

Example

Dim dateExpression

dateExpression = #10 March 2003#

If IsDate (dateExpression) Then
 MsgBox DateValue(dateExpression)
Else
 MsgBox "Invalid date"
End If

Programming Tips and Gotchas

  • When working with dates, always check that a date is valid using the IsDate function prior to passing it as a function parameter.
  • If stringexpression includes time information as well as date information, the time information is ignored; however, if only time information is passed to DateValue, an error is generated.
  • DateValue handles two-digit years in the following manner: year arguments between 0 and 29 are taken to be in the 21st Century (2000 to 2029), and year arguments between 30 and 99 are taken to be in the 20th Century (1930 to 1999). The safest way to specify a year is to use the full four digits.
  • The current formats being used for dates are easier to discover on Windows NT than on Windows 9x. On Windows NT, the date formats are held as string values in the following registry keys:

    Date Separator

    HKEY_CURRENT_USERControl PanelInternational, sDate value entry

    Long Date

    HKEY_CURRENT_USERControl PanelInternational, sLongDate value entry

    Short Date

    HKEY_CURRENT_USERControl PanelInternational, sShortDate value entry

  • The more common approach to date conversion is to use the CDate function. Microsoft also recommends using CDate and the other C... conversion functions due to their enhanced capabilities and their locale awareness.

See Also

CDate Function, DateSerial Function, IsDate Function

Day Function  

Syntax

Day(dateexpression)

dateexpression

Use: Required

Data Type: Any valid date expression

Any expression capable of conversion to a Date.

Return Value

Variant of type Integer.

Description

Returns a variant integer data type that can take on a value ranging from 1 to 31, representing the day of the month of dateexpression. dateexpression, the argument passed to the Day function, must be a valid date/time or time value.

Rules at a Glance

  • dateexpression can be any variant, numeric expression, or string expression that represents a valid date.
  • The range of dateexpression is 1/1/100 to 12/31/9999.
  • If dateexpression is Null, Null is returned.

Programming Tips and Gotchas

  • When working with dates, always check that a date is valid using the IsDate function prior to passing it as a function parameter.
  • If dateexpression omits the year, Day still returns a valid day.
  • If the day portion of dateexpression is outside its valid range, the function generates runtime error 13, "Type mismatch." This is also true if the day and month portion of dateexpression is 2/29 for a nonleap year.
  • To return the day of the week, use the WeekDay function.

See Also

DatePart Function, Weekday Function, WeekdayName Function, Month Function, Year Function

Dictionary Object  

Createable

Yes

Library

Microsoft Scripting Runtime

Description

The Dictionary object is similar to a Collection object, except that it's loosely based on the Perl associative array. Like an array or a Collection object, the Dictionary object holds elements, called items or members, containing data. A Dictionary object can contain any data whatsoever, including objects and other Dictionary objects. Access the value of these dictionary items by using unique keys (or named values) that are stored along with the data, rather than by using an item's ordinal position as you do with an array. This makes the Dictionary object ideal when you need to access data that is associated with a unique named value.

You can access each item stored to a Dictionary object by using the For Each ...Next construct. However, rather than returning a variant containing the data value stored to the Dictionary object as you would expect, it returns a variant containing the key associated with the member. You then have to pass this key to the Item method to retrieve the member, as the following example shows:

Dim vKey 
Dim sItem, sMsg 
Dim oDict 
 
Set oDict = CreateObject("Scripting.Dictionary")
oDict.Add "One", "Engine"
oDict.Add "Two", "Wheel"
oDict.Add "Three", "Tire"
oDict.Add "Four", "Spanner"
 
For Each vKey In oDict
 sItem = oDict.Item(vKey)
 sMsg = sMsg & sItem & vbCrLf
Next
 
MsgBox sMsg

Dictionary Object Properties

The Dictionary object includes the following four properties:

Property

Description

CompareMode

Determines the order of text comparisons in the Item property

Count

Indicates the total number of items in the dictionary

Item

Sets or retrieves a particular item of data in the dictionary

Key

Renames an existing key

Dictionary Object Methods

The Dictionary object supports the following five methods:

Property

Description

Add

Adds an item and its associated key to the dictionary

Exists

Determines whether a particular key exists in the dictionary

Keys

Returns all keys in the dictionary

Remove

Removes an item from the dictionary

Remove All

Removes all the data from the dictionary

Dictionary.Add Method  

Syntax

dictionaryobject.Add key, item

dictionaryobject

Use: Required

Data Type: Dictionary object

A reference to a Dictionary object.

key

Use: Required

Data Type: Any

A key value that's unique in the Dictionary object.

item

Use: Required

Data Type: Any

The item to be added to the dictionary.

Description

Adds a key and its associated item to the specified Dictionary object.

Rules at a Glance

  • If the key isn't unique, runtime error 457, "This key is already associated with an element of this collection," is generated.
  • item can be of any data type, including objects and other Dictionary objects.

Example

The example uses a Dictionary object to store state abbreviations and their corresponding state names:

Dim StateCode, StateName
Dim StateDict
Dim Key

Set StateDict = CreateObject("Scripting.Dictionary")

StateCode = "CA"
StateName = "California"
StateDict.Add StateCode, StateName

StateCode = "NY"
StateName = "New York"
StateDict.Add StateCode, StateName

StateCode = "MI"
StateName = "Michigan"
StateDict.Add StateCode, StateName

Key = "NY"
MsgBox StateDict.Item(Key)

Programming Tips and Gotchas

  • The order of members within a Dictionary object is officially undefined. That is, you can't control the position of individual members, nor can you retrieve individual members based on their position within the Dictionary object. Your code, in short, should make no assumptions about the position of individual elements within the Dictionary objects.
  • Once you add a key and its associated data item, you can change the key by using the write-only Key property.
  • Use the Dictionary object to store tables of data, and particularly to store single items of data that can be meaningfully accessed by a key value.
  • The use of the Dictionary object to store multifield data records is not recommended; instead, classes offer a better programmatic alternative. Typically, you would store a record by adding an array representing the record's field values to the dictionary. But assigning arrays to items in the Dictionary object is a poor programming practice, since individual elements of the array cannot be modified directly once they are assigned to the dictionary.

See Also

Dictionary.Key Property

Dictionary.CompareMode Property  

Data Type

Long

Description

Sets or returns the mode used to compare the keys in a Dictionary object.

Rules at a Glance

  • CompareMode can be set only on a dictionary that doesn't contain any data.
  • The CompareMode property can have either of the following two values:

    0, Binary

    This is the default value. It compares the keys with a string byte-per-byte to determine whether a match exists.

    1, Text

    Uses a case-insensitive comparison when attempting to match keys with a string.

    In addition, the value of CompareMode can be greater than 2, in which case it defines the locale identifier (LCID) to be used in making the comparison.

Programming Tips and Gotchas

  • You need to explicitly set the CompareMode property only if you do not wish to use the default binary comparison mode.
  • The Scripting Runtime type library defines constants (BinaryCompare and TextCompare) that can be used in place of their numeric equivalents. You can do this in one of three ways. You can define the constants yourself by adding the following code to your script:

    Const BinaryCompare = 0
    Const TextCompare = 1

    You can also use the equivalent vbBinaryCompare and vbTextCompare constants that are defined in the VBScript library.

    Finally, if you're an ASP programmer, you can use the METADATA directive to access the Scripting Runtime type library; if you're developing a Windows Script Host script, you can include the following line in a Windows Script Host (.wsf ) file in order to access the constants from the Scripting Runtime type library:

    
     
  • Practically, the CompareMode property indicates whether the comparison between existing key names and the key argument of the Dictionary object's Add method, Exists method, Item property, or Key property will be case-sensitive (BinaryCompare) or case-insensitive (TextCompare). By default, comparisons are case-sensitive.
Dictionary.Count Property  

Data Type

Long

Description

A read-only property that returns the number of key/item pairs in a Dictionary object.

Rules at a Glance

This property returns the actual number of items in the dictionary. So if you use the Count property to iterate the items in the dictionary, you would use code like the following:

Dim ctr
For ctr = 0 to dictionary.Count - 1
 ' do something
Next
Dictionary.Exists Method  

Syntax

dictionaryobject.Exists(key) 

dictionaryobject

Use: Required

Data Type: Dictionary object

A reference to a Dictionary object.

key

Use: Required

Data Type: String

The key value being sought.

Return Value

Boolean

Description

Determines whether a given key is present in a Dictionary object.

Rules at a Glance

Returns True if the specified key exists in the Dictionary object; False if not.

Programming Tips and Gotchas

  • If you attempt to use the Item property to return the item of a nonexistent key, or if you assign a new key to a nonexistent key, the nonexistent key is added to the dictionary, along with a blank item. To prevent this, you should use the Exists property to ensure that the Key is present in the dictionary before proceeding.
  • The way in which key is compared with the existing key values is determined by the setting of the Dictionary object's CompareMode property.

Example

If oDict.Exists(strOldKey) Then
 oDict.Key(strOldKey) = strNewKey
End If 

Dictionary Object ExampleEnter your name and location:

Your name:

Your location: ,

The ASP page that retrieves the information submitted by the user, encodes it, and uses the Dictionary object to retrieve the full state name is as follows:


 

ASP Page for the Dictionary Object Example<% Show Greeting %>

Dictionary.Item Property  

Syntax

The syntax for setting an item is:

dictionaryobject.Item(key) = item

The syntax for returning an item is:

value = dictionaryobject.Item(key)

dictionaryobject

Use: Required

Data Type: Dictionary object

A reference to a Dictionary object.

key

Use: Required

Data Type: String

A unique string key for this Dictionary object.

item

Use: Optional

Data Type: Any

The data associated with key.

Data Type

Any

Description

Sets or returns the data item to be linked to a specified key in a Dictionary object.

Rules at a Glance

  • The Item property is the default member of the Dictionary object.
  • The data type is that of the item being returned.
  • Unlike the Item property of most objects, the Dictionary object's Item property is read/write. If you try to set item to a nonexistent key, the key is added to the dictionary, and the item is linked to it as a sort of "implicit add."

Programming Tips and Gotchas

  • The Dictionary object doesn't allow you to retrieve an item by its ordinal position.
  • If you provide a nonexistent key when trying to retrieve an item, the dictionary exhibits rather strange behavior: it adds key to the Dictionary object along with a blank item. You should therefore use the Exists method prior to setting or returning an item, as the example shows.
  • If the item to be assigned or retrieved from the Dictionary object is itself an object, be sure to use the Set keyword when assigning it to a variable or to the Dictionary object.
  • The comparison of key with member keys is defined by the value of the Dictionary object's CompareMode property.
  • Although the read/write character of the Dictionary object's Item property has its drawbacks, it also has its advantages. In particular, it makes it easy to overwrite or replace an existing data item, since its Item property is read/write: simply assign the new value like you would with any other property.
  • The Dictionary object should never be used to store HTML form or query data in Session scope in an ASP application. Since the Dictionary object is an apartment-threaded COM object, this has the effect of locking down the application to a single thread of execution.

Example

The example uses the Dictionary object as a lookup table to retrieve the state name that corresponds to the state code entered by the user. The HTML page that submits user information to the server is as follows:


 
Dictionary.Items Method  

Syntax

dictionaryobject.Items

dictionaryobject

Use: Required

Data Type: Dictionary object

A reference to a Dictionary object.

Return Value

A Variant array.

Description

Returns an array containing all the items in the specified Dictionary object.

Rules at a Glance

The returned array is always a zero-based variant array whose data type matches that of the items in the Dictionary object.

Programming Tips and Gotchas

  • The only way to directly access members of the Dictionary is via their key values. However, using the Items method, you can "dump" the data from the Dictionary into a zero-based variant array. The data items can then be accessed like an array in the normal way, as the following code shows:

    Dim vArray
    vArray = DictObj.Items
    For i = 0 to DictObj.Count -1
     Response.Write vArray(i) & "

    " Next I

  • The Items method retrieves only the items stored in a Dictionary object; you can retrieve all the Dictionary object's keys by calling its Keys method.

See Also

Dictionary.Keys Method

Dictionary.Key Property  

Syntax

dictionaryobject.Key(key) = newkey

dictionaryobject

Use: Required

Data Type: Dictionary object

A reference to a Dictionary object.

key

Use: Required

Data Type: String

The key of an existing dictionary item.

newkey

Use: Required

Data Type: String

A new unique key for this dictionary item.

Data Type

A String.

Description

Replaces an existing key with a new one.

Rules at a Glance

  • The Key property is write-only.
  • key, the existing key value, must exist in the dictionary or an error results.
  • newkey must be unique and must not already exist in the dictionary or an error results.
  • The comparison of key and newkey with existing key values is defined by the Dictionary object's CompareMode property.

Example

Private Function ChangeKeyValue(sOldKey, sNewKey)
'Assumes oDictionary is a public object
 If oDictionary.Exists(sOldKey) Then
 oDictionary.Key(sOldKey) = sNewKey
 ChangeKeyValue = True
 Else
 ChangeKeyValue = False
 End If
End Function

Programming Tips and Gotchas

  • Use the Key property to change the name of an existing key. Use the Add method to add a new key and its associated value to the Dictionary object. Use the Keys method to retrieve the names of all keys; this is especially useful when you don't know the names or the contents of the dictionary in advance.
  • Attempting to retrieve the key name (a nonsensical operation, since this amounts to providing the key's name in order to retrieve the key's name) generates an error, as does attempting to modify a key name that hasn't already been added to the dictionary.
  • Using a For Each...Next loop to iterate the members of a Dictionary object involves an implicit call to the Key property. In other words, each iteration of the loop returns a key, rather than a data item. To retrieve the member's data, you then must use its key value to access its data through the Item property. This is illustrated in the example for the Dictionary.Item property.
Dictionary.Keys Method  

Syntax

dictionaryobject.Keys

dictionaryobject

Use: Required

Data Type: Dictionary object

A reference to a Dictionary object.

Return Value

An array of strings.

Description

Returns an array containing all the Key values in the specified Dictionary object.

Rules at a Glance

The returned array is always a 0-based variant array whose data type is String.

Programming Tips and Gotchas

The Keys method retrieves only the keys stored in a Dictionary object. You can retrieve all the Dictionary object's items by calling its Items method. You can recall an individual data item by using the Dictionary object's Item property.

Example

Dim vArray
vArray = DictObj.Keys
For i = 0 to DictObj.Count -1
 Response.Write vArray(i) & "
"
Next
Dictionary.Remove Method  

Syntax

dictionaryobject.Remove key

dictionaryobject

Use: Required

Data Type: Dictionary object

A reference to a Dictionary object.

key

Use: Required

Data Type: String

The key associated with the item to be removed.

Description

Removes both the specified key and its associated data (i.e., its item) from the dictionary.

Rules at a Glance

If key doesn't exist, runtime error 32811, "Element not found," occurs.

Dictionary.RemoveAll Method  

Syntax

dictionaryobject.RemoveAll

dictionaryobject

Use: Required

Data Type: Dictionary object

A reference to a Dictionary object.

Description

Clears out the dictionary; in other words, removes all keys and their associated data from the dictionary.

Programming Tips and Gotchas

If you want to remove a selected number of members rather than the entire contents of the dictionary, use the Remove method.

Dim Statement  

Syntax

Dim varname[([subscripts])], varname[([subscripts])]

varname

Use: Required

Your chosen name for the variable.

subscripts

Use: Optional

Dimensions of an array variable.

Description

Declares and allocates storage space in memory for variables. The Dim statement is used either at the start of a procedure or the start of a global script block. In the first case, the variable declared using Dim is local to the procedure. In the second, it's available throughout the module.

Rules at a Glance

  • You can declare multiple variables in a single Dim statement, as long as you use a comma to delimit them.
  • When variables are first initialized with the Dim statement, they have a value of Empty. In addition, if a variable has been initialized but not assigned a value, the following expressions will both evaluate to True:

    If vVar = 0 Then 
    If vVar = "" Then
  • To declare array variables, use the following syntax:

    Fixed length, single dimension

    Dim arrayname(upper)

    Example: Dim myArray(10)

    Fixed length, multidimensional

    Dim arrayname(upper, upper, ...)

    Example: Dim MyArray(20,30)

    Variable length, single or multidimensional

    Dim arrayname( )

    Example: Dim myArray( )

  • You can declare a multidimensional array with up to 60 dimensions.
  • Variable-length arrays can be resized using the ReDim statement. Fixed-length arrays can't be resized.

Example

The example shows how to use the Dim statement to define a variable that receives an array returned by a function:

Dim Input, NumArray

Input = InputBox("Enter three numbers separated by commas: ")
NumArray = Split(Input, ",")
If IsEmpty(NumArray) Then
 MsgBox "No numbers were entered."
Else
 Dim Sum, Element
 For Each Element in NumArray
 If IsNumeric(Element) Then Sum = Sum + CDbl(Element)
 Next
 MsgBox "The total of the numbers is: " & Sum
End If

Programming Tips and Gotchas

  • It's accepted practice to place all the Dim statements to be used in a particular procedure at the beginning of that procedure, and to place all Dim statements for global variables at the beginning of the script block.
  • Variables declared with Dim in the global script block are available to all procedures within the script. At the procedure level, variables are available only within the procedure.

VBA/VBScript Differences

  • VBA allows you to instantiate objects of a particular type through early binding by using the New keyword. VBScript does not support the New keyword when used with Dim statement, nor does it support strong typing of objects.
  • VBA supports the use of the WithEvents keyword, which allows VBA code to trap the events fired by an object of a particular type (that is, by a strongly typed object). VBScript does not support the keyword and hence does not allow you to trap events that are not otherwise supported by the host object model. For instance, you can trap the Application_OnStart, Application_OnEnd, OnTransactionCommit, OnTransactionAbort, Session_OnStart, and Session_OnEnd events in an ASP application. (For details on events supported by each object model, see Chapter 5 through Chapter 8, which discuss the object models of each host environment that supports VBScript.) A partial exception to this lack of support for external events is Windows Script Host, which allows you to trap an object's events by supplying an extra parameter to the WScript.CreateObject method or by calling the WScript.ConnectObject method.
  • In VBA, only variables explicitly declared as variants and variables whose data type has not been declared are reported by the IsEmpty function to be empty, and return True when compared to zero or to a null string. This is true of all variables in VBScript, because it does not support strong typing.

See Also

Const Statement, Private Statement, Public Statement, ReDim Statement

Do . . . Loop Statement  

Syntax

Do [{While | Until} condition]
 [statements]
[Exit Do]
 [statements]
Loop

or:

Do
 [statements]
[Exit Do]
 [statements]
Loop [{While | Until} condition]

condition

Use: Optional

Data Type: Boolean expression

An expression that evaluates to True or False.

statements

Use: Optional

Program statements that are repeatedly executed while, or until, condition is True.

Description

Repeatedly executes a block of code while or until a condition becomes True.

Rules at a Glance

  • On its own, Do...Loop repeatedly executes the code that is contained within its boundaries indefinitely. You therefore need to specify under what conditions the loop is to stop repeating. Sometimes, this requires modifying the variable that controls loop execution within the loop. For example:

    Do
     intCtr = intCtr + 1 ' Modify loop control variable
     Response.Write "Iteration " & intCtr & _
     " of the Do loop..." & "
    "
     ' Compare to upper limit
     If intCtr = 10 Then Exit Do 
    Loop

    Failure to do this results in the creation of an endless loop.

  • Adding the Until keyword after Do instructs your program to Do something Until the condition is True. Its syntax is:

    Do Until condition
     code to execute
    Loop

    If condition is True before your code gets to the Do statement, the code within the Do...Loop is ignored.

  • Adding the While keyword after Do repeats the code while a particular condition is True. When the condition becomes False, the loop is automatically exited. The syntax of the Do While statement is:

    Do While condition
     code to execute
    Loop

    Again, the code within the Do...Loop construct is ignored if condition is False when the program arrives at the loop.

  • In some cases, you may need to execute the loop at least once. You might, for example, evaluate the values held within an array and terminate the loop if a particular value is found. In that case, you'd need to execute the loop at least once. To do this, place the Until or While keyword along with the condition after the Loop statement. Do...Loop Until always executes the code in the loop at least once and continues to loop until the condition is True. Likewise, Do...Loop While always executes the code at least once, and continues to loop while the condition is True. The syntax of these two statements is as follows:

    Do
     code to execute
    Loop Until condition
    
    Do
     code to execute
    Loop While condition
  • A Null condition is treated as False.
  • Your code can exit the loop at any point by executing the Exit Do statement.

Programming Tips and Gotchas

  • Inexperienced programmers often think that a loop exits as soon as the condition that terminates the loop is met. In fact, however, it exits whenever the conditional statement that evaluates the loop control expression is executed and that expression is True. For example, in the code:

    Do While X <> 10
     ' This always executes if the loop is entered
    
     ' Set loop termination variable
     X = 10
    
     ' Any code here still executes. There is nothing
     ' monitoring X
    Loop

    all statements following the assignment execute until the condition at the top of the loop is evaluated.

  • You'll also encounter situations in which you intend to continually execute the loop while or until a condition is True, except in a particular case. This type of exception is handled using the Exit Do statement. You can place as many Exit Do statements within a Do...Loop structure as you require. As with any exit from a Do...Loop, whether it's exceptional or normal, the program continues execution on the line directly following the Loop statement. The following code fragment illustrates the use of Exit Do:

    Do Until condition1
     'code to execute
     If condition2 Then
     Exit Do
     End if
     'more code to executeonly if condition2 is false
    Loop

See Also

For Each . . . Next Statement, For . . . Next Statement, While . . . Wend Statement

Drive Object  

Returned by

File.Drive property

FileSystemObject.Drives.Item property

Createable

No

Library

Microsoft Scripting Runtime

Description

Represents a single drive connected to the current machine, including a network drive. By using the Drive object, you can interrogate the system properties of any drive. In addition, you can use the Folder object returned by the Drive object's RootFolder property as your foothold into the physical drive's filesystem.

A new instance of the Drive object cannot be created. Instead, a Drive object that represents an existing physical drive typically is retrieved from the FileSystemObject object's Drives collection, as in the following code fragment, which retrieves an object reference that represents the C: drive:

Dim oFS, oDrive
Set oFS = CreateObject("Scripting.FileSystemObject")
set oDrive = oFS.Drives("C")

For an overview of the File System object model, including the library reference needed to access it, see the "File System Object Model" entry.

Properties

All Drive object properties are read-only. In addition, removable media drives must be ready (i.e., have media inserted) for the Drive object to read certain properties.

AvailableSpace

Data Type: Long

Returns the number of bytes unused on the disk. Typically, the AvailableSpace property returns the same number as the Drive object's FreeSpace property, although differences may occur on systems that support quotas. In early versions of the Scripting Runtime, AvailableSpace was capable of storing only values that ranged from 0 to 2^31, or 2,147,483,648; in other words, in the case of drives with over 2 GB free, it failed to accurately report the amount of available free space.

In order to check the amount of available space on the drive, the drive must be ready. Otherwise, an error is likely to result. This makes it worthwhile to check the value of the IsReady property before attempting to retrieve a drive's free space, particularly if your script is iterating the Drives collection.

DriveLetter

Data Type: String

The drive letter used for this drive on the current machine (e.g., C ). In addition, its value is an empty string ("") if the drive is a network share that has not been mapped to a local drive letter.

DriveType

Data Type: Long

A value (see the following table) indicating the type of drive. Any remote drive is shown only as remote. For example, a shared CD-ROM or Zip drive that is both remote and removable is shown simply as remote (i.e., it returns a value of 3) on any machine other than the machine on which it's installed.

Constant

Value

CDROM

4

Fixed

2

RAMDisk

5

Remote

3

Removable

1

Unknown

0

The Scripting Runtime type library defines the constants shown in the above table's Constant column that can be used in place of their numeric equivalents. You can take advantage of these constants in your scripts in one of two ways. You can define the constants yourself by adding the following code to your script:

Const Unknown = 0
Const Removable = 1
Const Fixed = 2
Const Remote = 3
Const CDRom = 4
Const RAMDisk = 5

You can also use the ASP METADATA tag to access the constants from the type library, or you can include the following line in a Windows Script Host (.wsf ) file in order to access the constants from the Scripting Runtime type library:


 

The DriveType property does not require that the drive be ready to return a value.

FileSystem

Data Type: String

The installed filesystem; returns FAT, FAT32, NTFS, or CDFS. In order to determine that the filesystem in place, a device must be present on removable drives or runtime error 71, "Disk not ready," results.

FreeSpace

Data Type: Long

The number of bytes unused on the disk. Typically, its value is the same as the Drive object's AvailableSpace property, although differences may occur on computer systems that support quotas.

In early versions of the scripting Runtime, the property was capable of storing only values that ranged from 0 to 231, or 2,147,483,648. In other words, in the case of drives with over 2 GB free, it failed to accurately report the amount of available free space.

IsReady

Data Type: Boolean

For hard drives, this should always return True. For removable media drives, True is returned if media is in the drive; otherwise, False is returned.

A number of Drive object properties raise an error if the drive they represent is not ready. You can use the IsReady property to check the status of the drive and prevent your script from raising an error.

Path

Data Type: String

The drive name followed by a colon (e.g., C:). (Note that it does not include the root folder.) This is the default property of the Drive object.

RootFolder

Data Type: Folder object

Gives you access to the rest of the drive's filesystem by exposing a Folder object representing the root folder.

SerialNumber

Data Type: Long

The serial number of the drive, an integer that uniquely identifies the drive or disk. If a disk or CD-ROM has been assigned a serial number, you can use this property to insure that the correct disk is present in a drive that has removable media.

ShareName

Data Type: String

For a network share, returns the machine name and share name in UNC format (e.g., NTSERV1TestWork). If the Drive object does not represent a network drive, the ShareName property returns a zero-length string ("").

TotalSize

Data Type: Double

The total size of the drive in bytes. In early versions of the Scripting Runtime, the TotalSize property was capable of storing only values that ranged from 0 to 231, or 2,147,483,648. In other words, in the case of drives larger than 2 GB, it failed to accurately report the total drive size.

In order to check the amount of total space on the drive, the drive must be ready. Otherwise, a "Disk not ready" error is likely to result. This makes it worthwhile to check the value of the IsReady property before attempting to retrieve a drive's free space, particularly if your script is iterating the Drives collection.

VolumeName

Data Type: String

The drive's volume name, if one is assigned (e.g., DRIVE_C). If a drive or disk has not been assigned a volume name, the VolumeName property returns an empty string (""). This is the only read/write property supported by the Drive object.

In order to retrieve the volume name, the drive must be ready. Otherwise, a "Disk not ready" error is likely to result. This makes it worthwhile to check the value of the IsReady property before attempting to retrieve a drive's volume name, particularly if your script is iterating the Drives collection.

Drives Collection Object  

Returned by

FileSystemObject.Drives property

Createable

No

Library

Microsoft Scripting Runtime

Description

All drives connected to the current machine are included in the Drives collection, even those that aren't currently ready (like removable media drives with no media inserted in them). The Drives collection object is read-only.

The Drives collection cannot be created; instead, it is returned by the Drives property of the FileSystemObject object, as the following code fragment illustrates:

Dim oFS, oDrives
Set oFS = CreateObject("Scripting.FileSystemObject")
Set oDrives = oFS.Drives

For an overview of the filesystem object model, including the library reference needed to access it, see the "File System Object Model" entry.

Properties

Count

Data Type: Long

Returns the number of Drive objects in the collection.

Item

Syntax: oDrives.Item(key)

Data Type: Drive object

Returns a Drive object whose key is key, the drive letter. This is an unusual collection, since the drive's index value (its ordinal position in the collection) can't be used; attempting to do so generates runtime error 5, "Invalid procedure call or argument." Since attempting to retrieve a Drive object for a drive that doesn't exist generates runtime error 68, it's a good idea to call the FileSystemObject object's DriveExists method beforehand.

Example

Dim ofsFileSys As FileSystemObject
Dim ofsDrives As Drives
Dim ofsDrive As Drive
 
Set ofsFileSys = New FileSystemObject
Set ofsDrives = ofsFileSys.Drives
Set ofsDrive = ofsDrives.Item("C")
MsgBox ofsDrive.DriveType

See Also

Drive Object, FileSystemObject.Drives Property

End . . . Statement  

Syntax

End Class
End Function 
End If
End Property 
End Select
End Sub
End With

Description

Ends a procedure or a block of code.

Rules at a Glance

The End statement is used as follows:

Statement

Description

End Class

Marks the end of a class definition

End Function

Marks the end of a Function procedure

End If

Marks the end of an If...Then...Else statement

End Property

Marks the end of a Property Let, Property Get, or Property Set procedure within a Class...End Class construct

End Select

Marks the end of a Select Case statement

End Sub

Marks the end of a Sub procedure

End With

Marks the end of a With statement

Programming Tips and Gotchas

The End statement used by itself to terminate the program is not supported within a VBScript script or procedure. Instead you should terminate execution of a procedure prematurely using the Exit... statement. You can also terminate the script or application by calling a method belonging to an object of the object model you are using. These are shown in the following table:

Environment

Method

ASP

Response.End or Session.Abandon

IE

Application.Quit

Outlook form

Item.Close

Windows Script Host

WScript.Quit

VBA/VBScript Differences

VBA supports the End statement, which immediately terminates execution of code and, in the case of Visual Basic, terminates the application. The End statement, however, is not supported in VBScript.

See Also

Exit Statement

Erase Statement  

Syntax

Erase arraylist

arraylist

Use: Required

Data Type: Variant array

A list of array variables to clear.

Description

Resets the elements of an array to their initial (unassigned) values. In short, Erase "clears out" or empties an array.

Rules at a Glance

  • Specify more than one array to be erased by using commas to delimit arraylist.
  • Fixed array variables remain dimensioned; on the other hand, all memory allocated to dynamic arrays is released.
  • After the Erase statement executes, TypeName returns "Variant( )" for a fixed-length array; in addition, the IsEmpty function returns True when individual members of the array are passed to it, and comparisons of an individual member of the array with an empty string ("") and with zero both return True. On the other hand, the TypeName function returns Empty for a dynamic array, and comparisons of the array with an empty string ("") and zero also return True.

Programming Tips and Gotchas

Once you use Erase to clear dynamic arrays, they must be redimensioned with ReDim before being used again. This is because Erase releases the memory storage used by the dynamic array back to the operating system, which sets the array to have no elements.

VBA/VBScript Differences

Because VBA can be strongly typed, the behavior of the Erase statement in clearing a fixed array varies, depending on the array's data type. The effect of the Erase statement on a fixed variant array in VBScript is described earlier in the "Rules at Glance" section.

See Also

Dim Statement, ReDim Statement

Err Object  

Description

The Err object contains properties and methods that allow you to obtain information about a single runtime error in a VBScript script. It also allows you to generate errors and to reset the error object. Because the Err object is an intrinsic object (which means that it's part of every VBScript script you create) with global scope, you don't need to create an instance of it within your code.

When an error is generated in your applicationwhether it's handled or notthe properties of the Err object are assigned values you can then access to gain information about the error that occurred. You can even generate your own errors explicitly using the Err.Raise method. You can also define your own errors to unify the error-handling process.

When your program reaches an On Error Resume Next or On Error Goto 0 statement, the Err object is cleared and its properties reinitialized. This can also be achieved explicitly using the Err.Clear method.

Properties

Property name

Description

Description

The string associated with the given error number

HelpContext

A context ID within a VBScript Help file

HelpFile

The path to a VBScript Help file

Number

A long integer used to describe an error (i.e., an error code)

Source

Either the name of the current project or the class name of the application that generated the error

Methods

Method name

Description

Clear

Resets all the properties of the Err object

Raise

Forces an error with a particular error code to be generated

Programming Tips and Gotchas

The VBScript Err object isn't a collection; it contains only information about the last error, if one occurred. You could, however, implement your own error collection class to store a number of errors by copying error information from the Err object into an object array that holds error information.

VBA/VBScript Differences

  • The VBA Err object includes one additional property, LastDLLError, that reports the last error code generated by a call to a DLL routine.
  • In VBA, the Err object is automatically reset whenever an Exit Function, Exit Sub, Exit Property, Resume, or On Error statement is encountered, the Err object is cleared, and its properties reinitialized. In VBScript, this occurs only when an On Error Resume Next or an On Error Goto 0 statement is executed.

See Also

Err.Clear Method, Err.Raise Method, On Error Statement

Err.Clear Method  

Syntax

Err.Clear

Description

Explicitly resets all the properties of the Err object after an error has been handled.

Rules at a Glance

You need to clear the Err object only if you need to reference its properties for another error within the same subroutine or before another On Error Resume Next statement within the same subroutine.

Example

On Error Resume Next
 
i = oObjectOne.MyFunction(iVar)
 
If Err.Number <> 0 Then
 MsgBox "The Error : " & Err.Description & vbCrLf _
 & " was generated in " & Err.Source
 Err.Clear
End If
 
j = oObjectTwo.YourFunction(iVar)
 
If Err.Number <> 0 Then
 MsgBox "The Error : " & Err.Description & vbCrLf _
 & " was generated in " & Err.Source
 Err.Clear
End If

Programming Tips and Gotchas

  • Resetting the Err object explicitly using the Clear method is necessary when you use On Error Resume Next and test the value of Err.Number repeatedly. Unless you reset the Err object, you run the very real risk of catching the previously handled error, the details of which are still lurking in the Err object's properties.
  • The Err object is automatically reset when an On Error Resume Next or On Error Goto 0 statement is executed.
  • It is also possible to set the Err.Number property to 0 instead of calling up the Err.Clear method. However, this doesn't reset the remaining properties of the Err object.
  • When testing the value of Err.Number, don't forget that OLE servers often return "negative" numbers. Actually internally they're not really negative, but are unsigned longs. However, since VBScript has no unsigned long data type, its value is represented as a negative number.

VBA/VBScript Differences

In VBA, the Err object is automatically reset by an Exit Function, Exit Sub, Exit Property, Resume, or On Error statement. In VBScript, it's reset only by an On Error statement.

See Also

Err Object, Err.Raise Method, On Error Statement

Register

Welcome!

Enter Your Name:

The source code for Err_Desc2.asp is:


 

Welcome to our Web Page<% On Error Resume Next Dim sFormName, sName sFormName = Server.HTMLEncode(Request.Form.Item("txtName")) sName = ValidateString(sFormName) If Err.Number = 0 Then Response.Write "

 

Welcome, " & sName & "." Else Response.Write "We encounter an error in the information you submitted: " & _ "

" & Err.Description End If %> Chapter 7

Programming Tips and Gotchas

  • If you raise an error with the Err.Raise method that does not correspond to a VBScript error and don't set the Description property, the Description property is automatically set to "Unknown runtime error."
  • You can also pass the Err.Description to a logging device such as a log file in Windows 95/98/ME or the application log in Windows NT/2000/XP by using the Windows Script Host WSHShell.LogEvent method; for details, see Chapter 7.
  • The best way to set the Description property for your own application-defined errors is to use the description argument with the Raise method:

    Err.Raise 65444,, "Meaningful Error Description"

VBA/VBScript Differences

In VBA, user-defined errors that do not have descriptions are automatically assigned a description of "Application Defined or Object Defined Error." In VBScript, the description is "Unknown runtime error."

See Also

Err Object, Err.Number Property, Err.Raise Method

Err.Description Property  

Data Type

String

Description

A read/write property containing a short string describing a runtime error.

Rules at a Glance

  • When a runtime error occurs, the Description property is automatically assigned the standard description of the error.
  • If there is no error (that is, if the value of Err.Number is 0), the value of the Description property is an empty string.
  • For user-defined errors (that is, for errors that you define in your own scripts), you must assign a string expression to the Description property or the error won't have an accompanying textual message.
  • You can override the standard description by assigning your own description to the Err object for both VBScript errors and user-defined errors.

Example

This example uses the description parameter of the Err.Raise method to return an error message when validating information from an HTML form. The web page containing the form is:


 
Err.HelpContext Property  

Data Type

Long

Description

A read/write property that either sets or returns a long integer value containing the context ID of the appropriate topic within a Help file.

Rules at a Glance

  • The HelpContext property can be set either directly or by supplying the fifth parameter (the helpcontext parameter) to the Err.Raise method.
  • HelpContext IDs are decided upon when writing and creating a Windows help file. Once the Help or HTML help file has been compiled, the IDs can't be changed. Each ID points to a separate Help topic.

Example

On Error Resume Next
 
Dim i

i = 8
MsgBox (i / 0)
If Err.Number <> 0 Then
 Err.Description = "You are attempting to divide by zero."
 Err.Helpfile = "C:WindowshelpCustomApp.CHM"
 Err.HelpContext = 1000000 + Err.Number
 MsgBox Err.Description, vbMsgBoxHelpButton, "Error", Err.HelpFile, _ 
 Err.HelpContext
End If

Programming Tips and Gotchas

  • You can display a topic from a help file by supplying values to the Err.HelpFile and Err.HelpContext properties, using the MsgBox function with the vbMsgBoxHelpButton constant and passing Err.HelpContext as the HelpContext argument (as shown in the previous example).
  • If you supply a HelpContext ID that can't be found in a Windows Help file, the contents page for the Help file should be displayed. However, what actually happens is that a Windows Help error is generated, and a message box is displayed that informs the user to contact their vendor. If you supply a HelpContextID that cannot be found in an HTML Help file, VBScript displays an error message indicating that the Help file is either invalid or corrupted.
  • In ASP applications, the HelpContext and HelpFile properties should not be used, since context-sensitive help on the server is undesirable. In Internet Explorer applications, particularly those that are accessible over the Internet, use of the HelpContext and HelpFile properties is not advisable, since you can't be certain that the appropriate help file is available on the client.

VBA/VBScript Differences

  • At runtime, the HelpFile and HelpContext properties are automatically set when a VBA runtime error is encountered either because of an actual error or because of a call to the Err.Raise method. When a VBScript-defined error is encountered, on the other hand, these property values are not updated, since it may not make sense to supply help in a scripted environment.
  • An invalid HelpContext ID to an HTML Help file causes VBA to display the file's Contents page. It causes VBScript to display an error message noting that the file either is not a help file or has been corrupted.

See Also

MsgBox Function, Err.HelpFile Property, Chapter 4

Err.HelpFile Property  

Data Type

String

Description

A read/write string property that contains the fully qualified path of a Windows Help or HTML Help file.

Rules at a Glance

The HelpFile property can be set either directly or by supplying the fourth parameter (the helpfile parameter) to the Err.Raise method.

Example

See Err.HelpContext.

Programming Tips and Gotchas

  • Some objects you may use within your application have their own help files, which you can access using HelpFile to display highly focused help to your users.
  • Remember that once the program encounters an On Error statement, all the properties of the Err object are reset; this includes HelpFile. You must therefore set the Err.HelpFile property each time your application needs to access the help file.
  • In ASP applications, the HelpContext and HelpFile properties should not be used, since context-sensitive help on the server is undesirable. In IE applications, particularly those that are accessible over the Internet, use of the HelpContext and HelpFile properties is not advisable, since you can't be certain that the appropriate help file is available on the client.

VBA/VBScript Differences

Much of the utility of the HelpFile and HelpContext properties in VBA stems from the fact that, for errors recognized by the runtime engine, these values are automatically supplied to the Err object and can in turn be passed to the MsgBox function. In VBScript, however, these values are not updated automatically; if you want to use a help file or implement context-sensitive help, you have to supply these values yourself.

See Also

Err.HelpContext Property, Err.Number Property, Chapter 4

Err.Number Property  

Data Type

Long

Description

A read/write property containing a type Long value that represents the error code for the last error generated.

Rules at a Glance

  • When a runtime error is generated within the program, the error code is automatically assigned to Err.Number.
  • The Number property is updated with an application-defined error whose code is passed as an argument to the Err.Raise method.
  • When using the Err.Raise method in normal code, your user-defined error codes can't be greater than 65536 or less than 0. (See the final note in the "Programming Tips and Gotchas" section of the entry for the Err.Raise method.)
  • VBScript uses error numbers in the range of 1-1058 as well as 32766-32767 and 32811 for its own trappable errors. In implementing a series of application-defined errors, your error handlers should either translate application errors into VBScript trappable errors or, preferably, assign a unique range to application-defined errors.
  • If your code instantiates an ActiveX server, its error codes should be increased by the value of the VBScript intrinsic constant vbObjectError. When control returns to the local application after an error has been raised by the OLE server, the application can determine that the error originated in the OLE server and extract the error number with a line of code like the following:

    Dim lError
    If ((Err.Number And &HFF00) And vbObjectError) Then
     lError = Err.Number XOr vbObjectError
Err.Raise Method  

Syntax

Err.Raise number, [source], [description], _
 [[helpfile], helpcontext]

number

Use: Required

Data Type: Long integer

A numeric identifier of the particular error.

source

Use: Optional

Data Type: String

The name of the object or application responsible for generating the error.

description

Use: Optional

Data Type: String

A useful description of the error.

helpfile

Use: Optional

Data Type: String

The fully qualified path of a Microsoft Windows Help or HTML Help file containing help or reference material about the error.

helpcontext

Use: Optional

Data Type: Long

The context ID within helpfile.

Description

Generates a runtime error.

Rules at a Glance

  • To use the Raise method, you must specify an error number.
  • If you supply any of the number, source, description, helpfile, and helpcontext arguments when you call the Err.Raise method, they are supplied as values to the Err object's Number, Source, Description, HelpFile, and HelpContext properties, respectively. Refer to the entries for the individual properties for full descriptions of and rules for each property.

Programming Tips and Gotchas

  • The Raise method doesn't reinitialize the Err object prior to assigning the values you pass in as arguments. This can mean that if you Raise an error against an Err object that hasn't been cleared since the last error, any properties you don't specify values for still contain the values from the last error.
  • As well as using Raise in a runtime scenario, you can put it to good use in the development stages of your program to test the viability of your error-handling routines under various circumstances.
  • The fact that Err.Number accepts only numbers in the range 0-65536 may appear to be strange at first because the data type of the Error Number parameter in the Raise event is a Long; however, deep in the recesses of the Err object, the error code must be declared as an unsigned integer, which is a data type not supported by VBScript.
  • When you raise an error in a scripted environment, it may not make sense to supply arguments to the helpfile and helpcontext parameters. They have no relevance to ASP applications; in IE applications, the help file itself may not be available on the host computer.

See Also

Err Object, Err.Clear Method, Err.HelpContext Property, Err.Number Property, Chapter 4

Err.Source Property  

Data Type

String

Description

A read/write string property containing the name of the application or the object that has generated the error.

Rules at a Glance

  • When a runtime error occurs in your code, the Source property is automatically assigned the string "Microsoft VBScript runtime error."
  • If the error occurs in an ActiveX component instantiated by your application, the Source property usually contains the class name or the programmatic identifier of the component that raised the error.

Programming Tips and Gotchas

Knowing what type of error has occurred within a program is often of little use if you don't know where the error was generated. However, if you enhance the standard Source property by adding the name of the procedure, class, property, or method when you raise an error, your debugging time can be cut dramatically.

See Also

Err Object, Chapter 4

Escape Function  

Syntax

Escape (string)
string

string

Use: Optional

Data Type: String

The String to be encoded.

Return Value

An encoded Variant of Type string.

Description

Returns an encoded version of string.

Rules at a Glance

  • All Unicode characters 255 and below are converted to %xx format except for A-Z, a-z, 0-9, and _*+-./@. For example, a space is replaced by %20.

Programming Tips and Gotchas

  • The Escape function is not documented in the VBScript documentation.
  • The function corresponds to the JScript escape method.
  • You can use the Escape function to encode an HTML document so that a web browser displays the HTML source rather than interprets it. Alternatively, you can use the HTMLEncode method of the ASP Server object to achieve a similar (and more readable) result.
  • You can use the Escape function to encode an HTTP query string before returning it to a web server.
  • If string contains no spaces, punctuation characters, accented characters, or non-ASCII characters, the Escape function simply returns string unchanged.

Example

The following is a very simple routine that allows you to experiment with encoding character strings:

Option Explicit

Dim sIn, sOut
Do While True
 sIn = InputBox("Enter a string:", "UnescapedString", "")
 If sIn = " Then Exit Do

 sOut = Escape(sIn)

 msgbox "In: " & sIn & vbcrlf & _
Loop

For example, the string:

This is a level-1 head: 

Hello!

returns the string:

This%20is%20a%20level-1%20head%3A%20%3CH1%3EHello%21%3C/H1%3E

VB/VBA Differences

This function is not supported in VBA.

See Also

Unescape Function

Eval Function  

Syntax

[result = ]Eval(expression)

result

Use: Optional

Data Type: Any

A variable to hold the result of the Eval function.

expression

Use: Required

Data Type: String

The expression to be evaluated.

Return Value

Any

Description

Evaluates an expression and returns the results.

Rules at a Glance

  • Eval follows the rules of precedence in evaluating expression.
  • If an equals sign (=) occurs in expression, it is interpreted as a comparison operator rather than as an assignment operator. In this case, Eval returns True if the parts of expression are equal and False if they are not.

Example

In this example, the first result will always evaluate to False, since the variables are not equal, and the second will always evaluate to True, since Test1 is in fact less than Test2:

Dim Test1, Test2, Result

Test1 = 4
Test2 = 5
Result = Eval("Test1 = Test2")
MsgBox Result
Result = Eval("Test1 < Test2")
MsgBox Result
Result = Eval("Test1 / Test2")
MsgBox Result
Result = Eval("Test1 - Test2")
MsgBox Result

Programming Tips and Gotchas

You may wonder why you'd want to bother with Eval when you can do the same thing without it. For example:

 lVar1 = 2
 lVar2 = 3
 lResult = lVar1 + lVar2

is the same as:

 lVar1 = 2
 lVar2 = 3
 lResult = Eval(lVar1 + lVar2)

But the significance of Eval is that it evaluates expressions stored to strings. For example, the code:

 Dim sExp, result, a, b, c
 
 a = 10
 b = 20
 c = 30
 
 sExp = "a + b + c"
 
 result = eval(sExp)

returns 60. This means that you can build expressions and assign them to strings dynamically, then have them evaluated by passing them to the Eval function.

VBA/VBScript Differences

The Eval function is not supported in VBA.

See Also

Execute Statement

Execute Statement  

Syntax

Execute statement

statement

Use: Required

Data Type: String expression

A string expression containing one or more statements for execution.

Description

Executes one or more statements.

Rules at a Glance

  • statement must evaluate to a string that contains one or more executable statements. An executable statement is any call to a user-defined procedure or function, or any intrinsic VBScript command.
  • You can put multiple statements in the expression; separate them with colons.
  • You can also separate the arguments with embedded line breaks.
  • If statement includes an equal sign, it is interpreted as an assignment rather than an evaluation. For example, x = 3 assigns the value 3 to the variable x, rather than comparing the value of the variable x with 3.
  • In VBScript, a program fragment such as x=3 can be interpreted as both an assignment statement (assigning the value 3 to the variable x) or as a comparison expression (for example If x = 3 Then...) The Execute and ExecuteGlobal statements always treat strings of the form a = b as assignment statements. Use Eval to interpret strings of this form as expressions.

Example

The following is a corrected version of an example appearing in online help that appears to do nothing. In this case, the Execute statement is used to execute a procedure named Proc2, and the entire source code for the procedure is also stored to the string S that is passed to the Execute statement:

dim S

S = "Proc2 : "
S = S & "Sub Proc2 : " 
S = S & "Dim x : "
S = S & "x = 10 : " 
S = S & "MsgBox X : " 
S = S & "End Sub "

Execute S

But since the Execute statement only defines Proc2 as a procedure that's visible within the script block but does not execute it, we must also execute Proc2 as follows:

dim S

S = "Sub Proc2 : " 
S = S & "Dim x : "
S = S & "x = 10 : " 
S = S & "MsgBox X : " 
S = S & "End Sub "

Execute S
Proc2

Programming Tips and Gotchas

  • The Execute statement does for executable statements what the Eval function does for expressions: it allows you to dynamically (i.e., at runtime) assign code to a string and execute it by passing it to the Execute statement.
  • Be careful with this technique, since it can lead to very hard-to-read code.

VBA/VBScript Differences

The Execute statement is not supported by VBA. However, it is not unlike the CallByName function, which appeared for the first time in VBA 6.0. CallByName allows you to execute a routine whose name you store to a variable; hence, the name of the routine need not be determined at design time.

See Also

Eval Function, ExecuteGlobal Statement

ExecuteGlobal Statement  

Syntax

ExecuteGlobal statement

statement

Use: Required

Data Type: String

A string expression containing zero or more statements for execution.

Description

Executes zero or more statements in the global namespace of a script.

Rules at a Glance

  • statement must evaluate to a string containing one or more executable statements. An executable statement is any call to a user-defined procedure or function, or to an intrinsic VBScript command.
  • If statement contains multiple statements or lines of code, you can separate them with colons.
  • You can also separate statements or lines of code with embedded line breaks (i.e., vbCrLf).
  • If statement includes an equal sign, it is interpreted as an assignment rather than an evaluation. For example, x = 3 assigns the value 3 to the variable x, rather than comparing the value of the variable x with 3.
  • Code created by ExecuteGlobal is executed in the script's global namespace. The global namespace is the following:

    • In ASP and IE, code within a tag, but outside of individual functions or procedures.
    • In Outlook, form-level code outside of individual event handlers, functions, or procedures.
    • In WSH, code outside of individual functions and procedures.

Example

The example WSH script illustrates the difference between Execute and ExecuteGlobal. Each is called within the MainProc procedure to define a subroutine. Execute creates a procedure named Proc2; however, it is only visible if called from MainProc. ExecuteGlobal creates a procedure named Proc1 which is globally available throughout the script.

Option Explicit

Dim x
x = 10

MainProc
EndProc
'Proc2 ' procedure not visible

Sub MainProc
 Dim x
 x = 20
 ExecuteGlobal "Sub Proc1 : MsgBox x : End Sub"
 Execute "Sub Proc2 : MsgBox x : End Sub"
 Proc2 ' only callable from MainProc
 Proc1
End Sub

Sub EndProc
 Proc1
End Sub

Note that both Proc1 and Proc2 access the public variable x, even though a local variable x was visible in MainProc when the Execute statement created the Proc2 procedure. If we wanted to pass the local variable x to our routine, we'd have to redefine Proc2 to accept it as a parameter, as follows:

Execute "Sub Proc2(ByVal a) : MsgBox a : End Sub"

Programming Tips and Gotchas

  • While the Execute statement executes code that inherits the scope of the procedure in which it was declared, ExecuteGlobal always executes code in the script's global scope. This has two major implications:

    • After the ExecuteGlobal statement runs, functions, procedures, or classes defined using ExecuteGlobal can be accessed from anywhere within the script.
    • Any variables accessed from code defined by the ExecuteGlobal statement must have global scope. In other words, when using ExecuteGlobal in a local scope, ExecuteGlobal will not see local variables.

VBA/VBScript Differences

The ExecuteGlobal statement is not supported by VBA.

See Also

Eval Function, Execute Statement

Exit Statement  

Syntax

Exit Do
Exit For
Exit Function
Exit Property
Exit Sub

Description

Prematurely exits a block of code.

Rules at a Glance

Exit Do

Exits a Do...Loop statement. If the current Do...Loop is within a nested Do...Loop, execution continues with the next Loop statement wrapped around the current one. If, however, the Do...Loop is standalone, program execution continues with the first line of code after the Loop statement.

Exit For

Exits a For...Next loop. If the current For...Next is within a nested For...Next loop, execution continues with the next Next statement wrapped around the current one. If, however, the For...Next loop is standalone, program execution continues with the first line of code after the Next statement.

Exit Function

Exits the current function.

Exit Property

Exits the current property procedure.

Exit Sub

Exits the current sub procedure.

Programming Tips and Gotchas

  • Traditional programming theory recommends one entry point and one exit point for each procedure. However, you can improve the readability of long routines by using the Exit statement. Using Exit Sub can save having to wrap almost an entire subroutine (which could be tens of lines long) within an If...Then statement.

    With Exit Sub:

    Sub MyTestSub(iNumber)
     If iNumber = 10 Then
     Exit Sub
     End If
     ...'code
    End Sub

    Without Exit Sub:

    Sub MyTestSub(iNumber)
     If iNumber <> 10 Then
     ...'code
     End If
    End Sub
  • In the case of the Exit Function, Exit Property, and Exit Sub statements, the point in the program to which program flow returns depends on the caller of the property, function, or sub, respectively, and not on the property, function, or sub itself.

See Also

Do . . . Loop Statement, For . . . Next Statement, For Each . . . Next Statement, Function Statement, Property Get Statement, Property Let Statement, Property Set Statement, Sub Statement

Exp Function  

Syntax

Exp(number)

number

Use: Required

Data Type: Number

Any valid numeric expression.

Return Value

A Double representing the antilogarithm of number.

Description

Returns the antilogarithm of a number; the antilogarithm is the base of natural logarithms, e (whose value is the constant 2.7182818), raised to a power.

Rules at a Glance

The maximum value for number is 709.782712893.

Programming Tips and Gotchas

Exp is the inverse of the Log function.

See Also

Log Function

File Object  

Createable

No

Returned by

Files.Item property

FileSystemObject.GetFile method

Library

Microsoft Scripting Runtime

Description

The File object represents a disk file that can be a file of any type and allows you to interrogate the properties of the file and to move upward in the filesystem hierarchy to interrogate the system on which the file resides. The process of instantiating a File objectfor example, assigning a reference from the File object's Item property to a local object variabledoesn't open the file. An open file is represented in the File System object model by a TextStream object, which can be generated by the File object's OpenAsTextStream method.

There are several methods of retrieving a reference to an existing File object:

  • If you want to work with a particular file, you can retrieve a reference to it directly by calling the GetFile method of the FileSystemObject object. For example:

    Dim oFS, oFile 
    Set oFS = CreateObject("Scripting.FileSystemObject")
    Set oFile = oFS.GetFile("C:DocumentsMyReport.doc")

    allows you to retrieve a reference to a File object representing the MyReport.doc file without having to use the File System object model to navigate the filesystem.

  • If you want to work with a file as a member of a folder or of a set of files, you can retrieve a reference to a File object that represents it from the Item property of the Files collection. (The Files collection is returned by the Files property of a Folder object.) The following code fragment, for instance, retrieves a reference to a file named MyReport.doc that is a member of the Documents folder:

    Dim oFS, oFile
    Set oFS = CreateObject("Scripting.FileSystemObject")
    Set oFile = oFS.Drives("C").RootFolder.SubFolders("Documents"). _
     Files("MyReport.doc")

    Note that a File object represents an existing file; you cannot create a File object representing a new file. (You can, however, create a new TextStream object that represents a new text file by calling the Folder object's CreateTextFile method.)

Properties

Attributes

Data Type: Long

Sets or returns the file's attributes. The value of the property represents a bit mask consisting of six flags in the case of a File object, each of which represents a particular file attribute. These values are:

Value

Description

1

Read-only

2

Hidden

4

System

32

Archive

1024

Alias

2048

Compressed

All flags are read/write except for the alias and compressed flags. A value of 0 (normal) indicates that no flags are set.

The attribute flags are represented by the constants of the FileAttribute enumeration in the Scripting Runtime library. You can access them from an ASP page by including the METADATA tag, or from a WSH script by including the following line in a Windows Script Host (.wsf ) file:


 

You can also add Const statements that define the attribute constants.

DateCreated

Data Type: Date

The date and time the file was created; the property is read-only.

DateLastAccessed

Data Type: Date

The date and time the file was last accessed. Whether the property includes the date and time or only the date depends on the operating system; Windows 95, Windows 98, and Windows ME, for instance, only return the date, while Windows NT, Windows 2000, and Windows XP return the date and time. The property is read-only.

DateLastModified

Data Type: Date

The date and time the file was last modified; the property is read-only.

Drive

Data Type: Drive object

Returns a Drive object representing the drive on which the file resides; the property is read-only.

Name

Data Type: String

The name of the file. Modifying the value of a File object's Name property renames the file.

ParentFolder

Data Type: Folder object

Returns a Folder object representing the folder in which the file resides; the property is read-only.

Path

Data Type: String

Returns the full path to the file from the current machine, including drive letter or network path/share name; the property is read-only. Path is the default property of the File object.

ShortName

Data Type: String

Returns a DOS 8.3 filename.

ShortPath

Data Type: String

Returns a DOS 8.3 folder name. The property is read-only.

Size

Data Type: Long

Returns the size of the file in bytes. The property is read-only.

The Size property holds a long integer, meaning that it accurately reports file sizes from 0 to 2,147,483,648 bytes. In previous versions of VBScript, the property failed to accurately report the size of large files of over 2 GB.

Type

Data Type: String

Returns a string containing the registered type description. This is the type string displayed for the file in Windows Explorer. If a file doesn't have an extension, the type is simply "File." When a file's type isn't registered, the type appears as the extension and "File." The property is read-only.

Methods

Copy

Move

Delete

OpenAsTextStream

File.Copy Method  

Syntax

oFileObj.Copy Destination [, OverwriteFiles]

oFileObj

Use: Required

Data Type: File object

A File object.

Destination

Use: Required

Data Type: String

The path and, optionally, the filename of the copied file.

OverwriteFiles

Use: Optional

Data Type: Boolean

True if the copy operation can overwrite an existing file, False otherwise.

Description

Copies the file represented by oFileObj to another location.

Rules at a Glance

Wildcard characters can't be used in Destination.

Programming Tips and Gotchas

  • If the Destination path is set to read-only, the Copy method fails regardless of the OverwriteFiles setting and generates a "Permission denied" error.
  • If OverwriteFiles is False and the file already exists in Destination, runtime error 58, "File Already Exists," is generated.
  • If the user has adequate rights, Destination can be a network path or share name. For example:

    MyFile.Copy "\NTSERV1d$RootTwo"
    MyFile.Copy "\NTSERV1RootTest"

See Also

FileSystemObject.CopyFile Method

File.Delete Method  

Syntax

oFileObj.Delete [Force]

oFileObj

Use: Required

Data Type: File object

A File object.

Force

Use: Optional

Data Type: Boolean

If set to True, ignores the file's read-only flag (if it's on), and deletes the file.

Description

Removes the current file.

Rules at a Glance

  • The Delete method deletes a file permanently; it does not move it to the Recycle Bin.
  • If the file is open, the method fails with a "Permission Denied" error.
  • The default setting for Force is False.
  • If Force is set to False, and the file is read-only, the method will fail.

Programming Tips and Gotchas

  • Unlike the FileSystemObject object's DeleteFile method, which accepts wildcard characters in the path parameter and can therefore delete multiple files, the Delete method deletes only the single file represented by oFileObj.
  • As a result of the Delete method, the Files collection object containing oFileObj is automatically updated, the deleted file is removed from the collection, and the collection count is reduced by one. You shouldn't try to access the deleted file object again; you should set oFileObj to Nothing.

See Also

FileSystemObject.DeleteFile Method

File.Move Method  

Syntax

oFileObj.Move destination

oFileObj

Use: Required

Data Type: File object

A File object.

destination

Use: Required

Data Type: String

The path to the location where the file is to be moved.

Description

Moves a file from one folder to another.

Rules at a Glance

  • The file represented by oFileObj must not be open or an error occurs.
  • Wildcard characters can't be used in Destination.
  • Destination can be either an absolute or a relative path.

Programming Tips and Gotchas

  • If a fatal system error occurs during the execution of this method (like a power failure), the worst that can happen is that the file is copied to the destination but not removed from the source. There are no rollback capabilities built into the File.Move method; however, because the copy part of this two-stage process is executed first, the file can't be lost.
  • If a folder or a file by the same name already exists in destination, the method generates runtime error 58, "File exists." To prevent this, you can use the FileSystemObject's FileExists and GetAbsolutePath methods prior to calling the Move method.
  • Unlike the FileSystemObject's MoveFile method, which accepts wildcard characters in the path parameter and can therefore move multiple files, the Move method moves only the single file represented by oFileObj.
  • As a result of the Move method, the Files collection object originally containing oFileObj is automatically updated, the file is removed from it, and the collection count is reduced by one. You shouldn't try to access the moved file object again in the same Folders collection object.
  • oObj, the File object reference, remains valid after the file has been moved. Its relevant properties (the Drive, ParentFolder, Path, and ShortPath properties, for example) are all updated to reflect the file's new path after the move.
  • If the user has rights, destination can be a network path or share name:

    oFile.Move "\NTSERV1d$RootTwomyfile.doc"

See Also

FileSystemObject.MoveFile Method

File.OpenAsTextStream Method  

Syntax

oFileObj.OpenAsTextStream ([IOMode[, Format]])

oFileObj

Use: Required

Data Type: File object

A File object.

IOMode

Use: Optional

Data Type: Long

A constant specifying the purpose for opening the file.

Format

Use: Optional

Data Type: Long

A constant specifying ASCII or Unicode format.

Return Value

A TextStream object.

Description

Opens the referenced text file for reading or writing.

Rules at a Glance

  • IOMode can be one of the following values:

    Constant

    Value

    Description

    ForAppending

    8

    Opens the file in append mode; that is, the current contents of the file are protected, and new data written to the file is placed at the end of the file.

    ForReading

    1

    Opens the file for reading; you can't write to a file that has been opened for reading.

    ForWriting

    2

    Opens the file for writing; all previous file content is overwritten by new data.

    The default value is 1, ForReading.

  • The Scripting Runtime type library defines constants of the IOMode enumeration that can be used in place of their numeric equivalents for the IOMode argument. You can use them in your scripts in either of two ways. You can define the constants yourself by adding the following code to your script:

    Const ForReading = 1
    Const ForWriting = 2
    Const ForAppending = 8

    You can also include the ASP METADATA tag in global.asa or include the following line in a Windows Script Host (.wsf ) file in order to access the constants from the Scripting Runtime type library:

    
     
  • Unicode can be one of the following values:

    Constant

    Value

    Description

    TristateUseDefault

    -2

    Open as System default

    TristateTrue

    -1

    Open as Unicode

    TristateFalse

    0

    Open as ASCII

    The default value is 0 or ASCII (TristateFalse).

  • The Scripting Runtime type library defines constants of the Tristate enumeration that can be used in place of their numeric equivalents for the Unicode argument. You can use them in your scripts in either of two ways. You can define the constants yourself by adding the following code to your script:

    Const TristateFalse = 0
    Const TristateTrue = -1
    Const TristateUseDefault = -2

    You can also include the ASP METADATA tag in global.asa or include the following line in a Windows Script Host (.wsf ) file in order to access the constants from the Scripting Runtime type library:

    
     
  • If another process has opened the file, the method fails with a "Permission Denied" error.
  • The TextStream object is so named for a very good reason: it is designed to work with text files rather than binary files. Although it is possible to use the OpenAs TextStream method to open a binary file, an enormous number of subtle bugs may crop up when you manipulate binary data as text. Because of this, if you want to work with binary files, you should use some technology (like the ADO binary file object) or programming language (like C/C++) that's more amenable to processing binary files.

See Also

FileSystemObject.OpenTextFile Method , TextStream Object

File System Object Model  

Library to Reference

Microsoft Scripting Runtime (SCRRUN.DLL )

Description

The FileSystemObject is a boon for all developers using any variety of Visual Basic (VBScript, VBA, and VB). It simplifies the task of dealing with any type of file input and output and for dealing with the system file structure itself. Rather than resorting to complex calls to the Win32 API (or, in the case of VBScript, not being able to access the filesystem altogether), this object allows the developer to easily handle files and navigate the underlying directory structures. This is especially useful for those developers or administrators who are creating scripts that are used for system administration or maintenance.

The File System object model is available to both VB and VBA developers, but it is only intrinsically part of the VBScript scripting language. The File System object model allows you to interrogate, create, delete, and manipulate folders and text files.

To access the File System object model, you must first create an instance of the FileSystemObject object, the only externally createable object in the model. From there, you can navigate through the object model, as shown in the object hierarchy diagram in Figure 10-1. The FileSystemObject object can be instantiated with a code fragment like the following:

Dim oFS
Set oFS = CreateObject("Scripting.FileSystemObject")

Figure 10-1. The File System object model

figs/vbs2.1001.gif

It can also be instantiated using the object creation method of the host object model.

See Also

File Object, Files Collection Object, FileSystemObject Object, Folder Object, Folders Collection Object, TextStream Object

Files Collection Object  

Createable

No

Returned by

Folder.Files property

Library

Microsoft Scripting Runtime

Description

The Files collection object is one of the objects in the File System object model; for an overview of the model, including the library reference needed to access it, see the "File System Object Model" entry.

The Files collection object is a container for File objects that is returned by the Files property of any Folder object. All files contained in the folder are included in the Files collection object. You can obtain a reference to a Files collection object using a code fragment like the following:

Dim oFS, oFiles

Set oFS = CreateObject("Scripting.FileSystemObject")
Set oFiles = oFS.Drives("C:").RootFolder. _
 SubFolders("Windows").Files

This code returns the Files collection for the Windows folder.

You can obtain a reference to an individual File object using the Files collection object's Item property; this takes the exact filename, including the file extension, as an argument. To iterate through the collection, you can use the For Each...Next statement. For details, see the entry for the File Object.

The Files collection object is read-only. Consequently, it supports only the following two properties.

Properties

Count

Data Type: Long

The number of File objects in the collection.

Item

Data Type: File object

Takes the filename (including the file extension) as a parameter and returns the File object representing the file with that name. Individual File objects can't be accessed by their ordinal position in the collection. Item is the Files collection object's default property. The code fragment shown next uses the Item property to retrieve the autoexec.bat File object.

Dim ofsFiles 
Dim ofsFile 

Set ofsFileSys = CreateObject("Scripting.FileSystemObject")
Set ofsFiles = ofsFileSys.Drives("C:").RootFolder.Files
Set ofsFile = ofsFiles.Item("autoexec.bat")
MsgBox ofsFile.DateCreated & vbCrLf & _
 ofsFile.DateLastModified & vbCrLf & _
 ofsFile.DateLastAccessed

See Also

File System Object Model, File Object

FileSystemObject Object  

Createable

Yes

Library

Microsoft Scripting Runtime

Description

The FileSystemObject object is at the top level of the File System object model and is the only externally createable object in the hierarchy; that is, it's the only object you can create using the CreateObject function or the host object model's object creation facilities. For example, the following code instantiates a FileSystemObject object named oFS:

Dim oFS
Set oFS = CreateObject("Scripting.FileSystemObject")

The FileSystemObject object represents the host computer's filesystem as a whole. Its members allow you to begin navigation into the filesystem, as well as to access a variety of common filesystem services. For information about the FileSystemObject object's properties and methods, see the entry for each property and method.

For an overview of the file system object model, see the "File System Object Model" entry.

Properties

Drives (returns a Drives collection object).

Methods

BuildPath

FileExists

GetFileName

CopyFile

FolderExists

GetFolder

CopyFolder

GetAbsolutePathName

GetParentFolderName

CreateFolder

GetBaseName

GetSpecialFolderd

CreateTextFile

GetDrive

GetTempName

DeleteFile

GetDriveName

MoveFile

DeleteFolder

GetExtensionName

MoveFolder

DriveExists

GetFile

OpenTextFile

FileSystemObject.BuildPath Method  

Syntax

oFileSysObj.BuildPath(Path, Name)

oFileSysObj

Use: Required

Data Type: FileSystemObject object

A FileSystemObject object.

Path

Use: Required

Data Type: String

A drive and/or folder path.

Name

Use: Required

Data Type: String

The folder or file path to append to path.

Return Value

A String.

Description

Creates a single string representing a path and filename or simply a path by concatenating the path parameter with the folder or filename, adding, where required, the correct path separator for the host system.

Rules at a Glance

  • Path can be an absolute or relative path and doesn't have to include the drive name.
  • Neither Path nor Name has to currently exist.

Programming Tips and Gotchas

  • BuildPath is really a string concatenation method rather than a filesystem method; it does not check the validity of the new folder or filename. If you intend that the method's return value be a path, you should check it by passing it to the FolderExists method; if you intend that the method's return value be a path and filename, you should verify it by passing it to the FileExists method.
  • The only advantage to using the BuildPath function as opposed to concatenating two strings manually is that the function selects the correct path separator.
FileSystemObject.CopyFile Method  

Syntax

oFileSysObj.CopyFile Source, Destination [, OverwriteFiles]

oFileSysObj

Use: Required

Data Type: FileSystemObject object

A FileSystemObject object.

Source

Use: Required

Data Type: String

The path and name of the file to be copied. The path can be relative or absolute, and the filename (but not the path) can contain wildcard characters.

Destination

Use: Required

Data Type: String

The path and optionally the filename of the copy to make. Destination cannot include wildcard characters.

OverwriteFiles

Use: Optional

Data Type: Boolean

Flag indicating whether an existing file is to be overwritten (True) or not (False). It's default value is True; files of the same names in the target folder will be overwritten.

Description

Copies a file or files from one folder to another.

Rules at a Glance

  • The default value for OverwriteFiles is True.
  • The source path can be relative or absolute.
  • The source filename can contain wildcard characters; the source path can't.
  • Wildcard characters can't be included in Destination.

Programming Tips and Gotchas

  • If the destination path or file is read-only, the CopyFile method fails, regardless of the value of OverwriteFiles and generates runtime error 70, "Permission Denied."
  • If OverwriteFiles is set to False and the file exists in Destination, a trappable errorruntime error 58, "File Already Exists"is generated.
  • If an error occurs while copying more than one file, the CopyFile method exits immediately, thereby leaving the rest of the files uncopied. There is no rollback facility to undo copies made prior to the error.
  • Both Source and Destination can include relative pathsthat is, paths that are relative to the current folder. The current folder is the folder in which the script is stored, the folder specified in the "Start in" text box of a shortcut, or the folder from which the script is launched from the console mode. The symbol to indicate the parent of the current folder is (..); the symbol to indicate the current folder is (.).
  • Source must include an explicit filename. For instance, under DOS, you could copy all of the files in a directory with a command in the format of:

    Copy c:data c:ckup

    or:

    Copy c:data c:ckup

    which would copy all the files from the C:data directory to C:ckup. The Source argument cannot take any of these forms; instead, you must include some filename component. For example, to copy all of the files from C:data, the CopyFile statement would take the form:

    oFS.CopyFile "C:data*.*", "C:ckup"
  • To specify multiple files, the Source argument can include the * and ? wildcard characters. Both are legacies from DOS. * matches any characters in a filename that follow those characters that are explicitly specified. For instance, a Source argument of File* matches File01.txt, File001.txt, and File.txt, since all three filenames begin with the string "File"; the remainder of the filename is ignored. ? is a wildcard that ignores a single character in a filename comparison. For instance, a Source argument of Fil?01.txt copies File01.txt and Fil_01.txt, since the fourth character of the filename is ignored in the comparison.
  • If you want the source and the destination directories to be the same, you can copy only a single file at a time, since Destination does not accept wildcard characters.
  • If the path specified in Destination does not exist, the method does not create it. Instead, it generates runtime error 76, "Path not found."
  • If the user has adequate rights, the source or destination can be a network path or share name. For example:

    CopyFile "c:Rootone*.*", "\NTSERV1d$RootTwo"
    CopyFile "\NTSERV1RootTest	est.txt", "c:RootOne"
  • The CopyFile method copies a file or files stored in a particular folder. If the folder itself has subfolders containing files, the method doesn't copy these; use the CopyFolder method.
  • The CopyFile method differs from the Copy method of the File object in two ways:

    • You can copy any file anywhere in a filesystem without having to first instantiate it as a File object.
    • You can copy multiple files in a single operation, rather than copying only the file represented by the File object.

See Also

FileSystemObject.CopyFolder Method, Folder.Copy Method

FileSystemObject.CopyFolder Method  

Syntax

oFileSysObj.CopyFolder Source, Destination [, OverwriteFiles]

oFileSysObj

Use: Required

Data Type: FileSystemObject object

A FileSystemObject object.

Source

Use: Required

Data Type: String

The path and name of the folder to be copied from.

Destination

Use: Required

Data Type: String

The path for the folder where the copy is to be made.

OverwriteFiles

Use: Optional

Data Type: Boolean

Flag indicating whether existing files are to be overwritten (True) or not (False). Its default value is True; files of the same name will be overwritten if they already exist in Destination.

Description

Copies the contents of one or more folders, including their subfolders, to another location.

Rules at a Glance

  • Source must end with either a wildcard character or no path separator. If it ends with a wildcard character, all matching subfolders and their contents will be copied. Wildcard characters can be used in Source only for the last component.
  • Wildcard characters can't be used in Destination.
  • All subfolders and files contained within the source folder are copied to Destination unless disallowed by the wildcard characters. That is, the CopyFolder method is recursive.
  • If Destination ends with a path separator or Source ends with a wildcard, CopyFolder assumes that the folder stated in Source exists in Destination or should otherwise be created. For example, given the following folder structure:

    C:
     Rootone
     SubFolder1
     SubFolder2
     RootTwo

    The code FileSys.CopyFolder "c:Rootone*", "C:RootTwo" produces this folder structure:

    C:
     Rootone
     SubFolder1
     SubFolder2
     RootTwo
     SubFolder1
     SubFolder2

    The code FileSys.CopyFolder "c:Rootone", "C:RootTwo" produces this folder structure:

    C:
     Rootone
     SubFolder1
     SubFolder2
     RootTwo
     Rootone
     SubFolder1
     SubFolder2

Programming Tips and Gotchas

  • If the destination path or any of the files contained in Destination are set to read-only, the CopyFolder method fails, regardless of the value of OverwriteFiles.
  • If OverwriteFiles is set to False, and the source folder or any of the files contained in Source exists in Destination, runtime error 58, "File Already Exists," is generated.
  • If an error occurs while copying more than one file or folder, the CopyFolder function exits immediately, leaving the rest of the folders or files uncopied. There is no rollback facility to undo the copies prior to the error.
  • If the user has adequate rights, both the source or destination can be a network path or share name. For example:

    CopyFolder "c:Rootone", "\NTSERV1d$RootTwo"
    CopyFolder "\NTSERV1RootTest", "c:RootOne"

See Also

Folder.Copy Method

FileSystemObject.CreateFolder Method  

Syntax

oFileSysObj.CreateFolder(Path)

oFileSysObj

Use: Required

Data Type: FileSystemObject object

A FileSystemObject object.

Path

Use: Required

Data Type: String

An expression that returns the name of the new folder to create.

Return Value

A Folder object.

Description

Creates a single new folder in the path specified and returns its Folder object.

Rules at a Glance

  • Wildcard characters aren't allowed in Path.
  • Path can be a relative or absolute path.
  • If no path is specified in Path, the current drive and directory are used.
  • If the last folder in Path already exists, the method generates runtime error, "File already exists."

Programming Tips and Gotchas

  • If Path is read-only, the CreateFolder method fails.
  • If Path already exists, the method generates runtime error 58, "File already exists."
  • If the user has adequate rights, Path can be a network path or share name. For example:

    CreateFolder "\NTSERV1d$RootTwo
    ewFolder"
    CreateFolder "\NTSERV1RootTest
    ewFolder"
  • You must use the Set statement to assign the Folder object to an object variable. For example:

    Dim oFileSys
    Dim oFolder
    Set oFileSys = CreateObject("Scripting.FileSystemObject")
    Set oFolder = oFileSys.CreateFolder("MyFolder")

See Also

Folders.Add Method

FileSystemObject.CreateTextFile Method  

Syntax

oFileSysObj.CreateTextFile Filename [, Overwrite[, Unicode]])

oFileSysObj

Use: Required

Data Type: FileSystemObject object

A FileSystemObject object.

Filename

Use: Required

Data Type: String

Any valid filename, along with an optional path.

Overwrite

Use: Optional

Data Type: Boolean

Flag indicating if an existing file of the same name should be overwritten.

Unicode

Use: Optional

Variant Sub Type: Boolean

Flag indicating if Filename is to be written in Unicode or ASCII.

Return Value

A TextStream object.

Description

Creates a new file and returns its TextStream object.

Rules at a Glance

  • Wildcard characters aren't allowed in Filename.
  • Filename can be a relative or absolute path.
  • If no path is specified in Filename, the script's current drive and directory are used. If no drive is specified in Filename, the script's current drive is used.
  • If the path specified in Filename doesn't exist, the method fails. To prevent this error, you can use the FileSystemObject object's FolderExists method to insure that the path is valid.
  • The default value for Overwrite is False.
  • If Unicode is set to True, the file is created in Unicode; otherwise, it's created as an ASCII text file. The default value for Unicode is False.

Programming Tips and Gotchas

  • The newly created text file is automatically opened only for writing. If you subsequently wish to read from the file, you must first close it and reopen it in read mode.
  • If the path referred to in Filename is set to read-only, the CreateTextFile method fails regardless of the value of Overwrite.
  • If the user has adequate rights, Filename can contain a network path or share name. For example:

    FileSys.CreateTextFile "\NTSERV1RootTestmyFile.doc"
  • You must use the Set statement to assign the TextStream object to your local object variable.
  • The CreateTextFile method of the Folder object is identical in operation to that of the FileSystemObject object.

See Also

Folder.CreateTextFile Method, TextStream Object

FileSystemObject.DeleteFile Method  

Syntax

oFileSysObj.DeleteFile FileSpec [, Force]

oFileSysObj

Use: Required

Data Type: FileSystemObject object

A FileSystemObject object.

FileSpec

Use: Required

Data Type: String

The name and path of the file or files to delete.

Force

Use: Optional

Data Type: Boolean

If set to True, the read-only flag on a file is ignored and the file deleted. Its default value is False; read-only files will not be deleted.

Description

Permanently removes a given file or files.

Rules at a Glance

  • FileSpec can contain wildcard characters as the final path component, which allows multiple files to be deleted.
  • FileSpec can be a relative or absolute path.
  • If any of the files specified for deletion are open, the method fails with a "Permission Denied" error.
  • If the specified file or files can't be found, the method fails.
  • If only a filename is used in FileSpec, the application's current drive and directory is assumed.

Programming Tips and Gotchas

  • If FileSpec specifies a path not ending in a path separator, the method will fail without generating an error. If FileSpec specifies a path that ends in a path separator, the method fails and generates runtime error 53, "File not found."
  • The DeleteFile method differs from the Delete method of the File object in several respects. First, it allows you to delete a file directly, without first obtaining an object reference to it. Second, by supporting wildcards, it allows you to delete multiple files at once.
  • If an error occurs while deleting more than one file, the DeleteFile method exits immediately, thereby leaving the rest of the files undeleted. There is also no rollback facility to undo deletions prior to the error.
  • If the user has adequate rights, the source or destination can be a network path or share name. For example:

    DeleteFile "\NTSERV1RootTestmyFile.doc"
  • DeleteFile permanently deletes files; it doesn't move them to the Recycle Bin.

See Also

Folder.Delete Method

FileSystemObject.DeleteFolder Method  

Syntax

oFileSysObj.DeleteFolder FileSpec[, Force]

oFileSysObj

Use: Required

Data Type: FileSystemObject object

A FileSystemObject object.

FileSpec

Use: Required

Data Type: String

The name and path of the folders to delete.

Force

Use: Optional

Data Type: Boolean

If set to True, the read-only flag on a file is ignored and the file deleted. By default, its value is False; read-only files will not be deleted.

Description

Removes a given folder and all its files and subfolders.

Rules at a Glance

  • FileSpec can contain wildcard characters as the final path component, which allows multiple folders that meet the file specification to be deleted.
  • FileSpec can't end with a path separator.
  • FileSpec can be a relative or absolute path.
  • If any of the files within the specified folders are open, the method fails with a "Permission Denied" error.
  • The DeleteFolder method deletes all contents of the given folder, including other folders and their contents.
  • If the specified folder can't be found, the method fails.

Programming Tips and Gotchas

  • If an error occurs while deleting more than one file or folder, the DeleteFolder method exits immediately, thereby leaving the rest of the folders or files undeleted. There is also no rollback facility to undo the deletions prior to the error.
  • DeleteFolder permanently deletes folders and their contents; it doesn't move them to the Recycle Bin.
  • The DeleteFolder method differs from the Delete method of the Folder object in two respects. First, it allows you to directly delete a folder, without first having to navigate to it or otherwise obtain an object reference to it. Second, it allows you to delete multiple folders, whereas the Delete method allows you to delete only the folder represented by the Folder object.
  • If the user has adequate rights, the source or destination can be a network path or share name. For example:
FileSys.DeleteFolder "\NTSERV1d$RootTwo"

See Also

Folder.Delete Method

FileSystemObject.DriveExists Method  

Syntax

oFileSysObj.DriveExists (DriveSpec)

oFileSysObj

Use: Required

Data Type: FileSystemObject object

A FileSystemObject object.

DriveSpec

Use: Required

Data Type: String

A path or drive letter.

Return Value

Boolean (True or False).

Description

Determines whether a given drive (of any type) exists on the local machine or on the network. The method returns True if the drive exists or is connected to the machine, and returns False if not.

Rules at a Glance

  • If DriveSpec is a Windows drive letter, it doesn't have to include the colon. For example, "C" works just as well as "C:".
  • Returns True if the drive exists or is connected to the machine, and returns False if not.

Programming Tips and Gotchas

  • DriveExists doesn't note the current state of removable media drives; for this, you must use the IsReady property of the Drive object representing the given drive.
  • If the user has adequate rights, DriveSpec can be a network path or share name. For example:

    If ofs.DriveExists("\NTSERV1d$") Then
  • This method is ideal for detecting any current drive around the network before calling a function in a remote ActiveX server located on that drive.
FileSystemObject.Drives Property  

Syntax

oFileSysObj.Drives

oFileSysObj

Use: Required

Variant Type: FileSystemObject object

A FileSystemObject object.

Return Value

Drives collection object.

Description

Drives is a read-only property that returns the Drives collection; each member of the collection is a Drive object, representing a single drive available on the system. Using the collection object returned by the Drives property, you can iterate all the drives on the system using a For...Next loop, or you can retrieve an individual Drive object, which represents one drive on the system, by using the Drives collection's Item method.

See Also

Drive Object, Drives Collection Object

FileSystemObject.FileExists Method  

Syntax

oFileSysObj.FileExists(FileSpec)

oFileSysObj

Use: Required

Data Type: FileSystemObject object

A FileSystemObject object.

FileSpec

Use: Required

Data Type: String

A complete path to the file.

Return Value

Boolean (True or False).

Description

Determines if a given file exists.

Rules at a Glance

  • Returns True if the file exists or is connected to the machine, and returns False if not.
  • FileSpec can't contain wildcard characters.
  • FileSpec can include either an absolute or a relative paththat is, a path that is relative to the current folder. The current folder is the folder in which the script is running, or the folder specified in the "Start in" text box of the shortcut used to launch the script. The symbol to indicate the parent of the current folder is (..); the symbol to indicate the current folder is (.). If FileSpec does not include a path, the current folder is used.

Programming Tips and Gotchas

If the user has adequate rights, FileSpec can be a network path or share name. For example:

If ofs.FileExists("\TestPathTest.txt") Then

See Also

FileSystemObject.FolderExists Method

FileSystemObject.FolderExists Method  

Syntax

oFileSysObj.FolderExists(FolderSpec)

oFileSysObj

Use: Required

Data Type: FileSystemObject object

A FileSystemObject object.

FolderSpec

Use: Required

Data Type: String

The complete path to the folder.

Return Value

Boolean (True or False).

Description

Determines whether a given folder exists; the method returns True if the Folder exists, and returns False if not.

Rules at a Glance

  • FolderSpec can't contain wildcard characters.
  • FolderSpec cannot include a filename as well as a path. In other words, the entire FolderSpec string can only include drive and path information.
  • If FolderSpec does not include a drive specification, the current drive is assumed.
  • FolderSpec is interpreted as an absolute path if it begins with a drive name and a path separator, and it is interpreted as an absolute path on the current drive if it begins with a path separator. Otherwise, it is interpreted as a relative path.

Programming Tips and Gotchas

  • If the user has adequate rights, FolderSpec can be a network path or share name. For example:

    If FileSys.FolderExists("\NTSERV1d$TestPath") Then
  • Among its string manipulation methods, the Scripting Runtime library lacks one that will extract a complete path from a path and filename. The example provides the GetCompletePath function to perform this useful task, as well as to illustrate the use of the FolderExists method.

Example

Function GetCompletePath(sPath)

Dim oFS
Dim sFileName, sPathName
Dim lPos

Set oFS = CreateObject("Scripting.FileSystemObject")

' Check if no backslash is present
If Instr(1, sPath, "") = 0 Then
 ' Determine if string is a filename
 If oFS.FileExists(sPath) Then
 ' Return current folder
 GetCompletePath = oFS.GetAbsolutePathName(".")
 Else
 ' Check if folder exists
 If oFS.FolderExists("" & sPath) Then
 GetCompletePath = sPath
 Else
 ' Raise "Path not found" error
 Err.Raise 76
 End If
 End If
' At least one backslash is present
Else
 ' check if last character is a backslash
 If Right(sPath, 1) = "" Then
 If oFS.FolderExists(sPath) Then
 GetCompletePath = sPath
 Else
 Err.Raise 76
 End If 
 ' Extract prospective filename from path
 Else 
 ' Check if the string includes a filename
 lPos = InstrRev(sPath, "")
 sFileName = Mid(sPath, lPos + 1)
 If oFS.FileExists(sPath) Then
 GetCompletePath = Left(sPath, lPos)
 Else
 ' Generate file not found error
 Err.Raise 53
 End If 
 End If
End If

End Function

See Also

FileSystemObject.DriveExists Method, FileSystemObject.FileExists Method

FileSystemObject.GetAbsolutePathName Method  

Syntax

oFileSysObj.GetAbsolutePathName(Path)

oFileSysObj

Use: Required

Data Type: FileSystemObject object

A FileSystemObject object.

Path

Use: Required

Data Type: String

A path specifier.

Return Value

A string containing the absolute path of a given path specifier.

Description

Converts a relative path to a fully qualified path, including the drive letter.

Rules at a Glance

  • (.) returns the drive letter and complete path of the current folder.
  • (..) returns the drive letter and path of the parent of the current folder.
  • If Path is simply a filename without a path, the method concatenates the complete path to the current directory with the filename. For example, if the current folder is C:DocumentsMyScripts, then the method call:

    sFileName = GetAbsolutePathName("MyFile.txt")

    produces the string "C:DocumentsMyScriptsMyFile.txt".

  • All relative pathnames are assumed to originate at the current folder. This means, for example, that (.) returns the drive letter and complete path of the current folder, and that (..) returns the drive letter and path of the parent of the current folder.
  • If a drive isn't explicitly provided as part of Path, it's assumed to be the current drive.
  • Wildcard characters can be included in Path at any point.

Programming Tips and Gotchas

  • An absolute path provides a complete route from the root directory of a particular drive to a particular folder or file. In contrast, a relative path describes a route from the current folder to a particular folder or file.
  • For mapped network drives and shares, the method doesn't return the full network address. Rather, it returns the fully qualified local path and locally issued drive letter.
  • The GetAbsolutePathName method is really a string conversion and concatenation method, rather than a filesystem method. It merely returns a string, but doesn't verify that a given file or folder exists in the path specified.
FileSystemObject.GetBaseName Method  

Syntax

oFileSysObj.GetBaseName(Path)

oFileSysObj

Use: Required

Data Type: FileSystemObject object

A FileSystemObject object.

Path

Use: Required

Data Type: String

A path specifier.

Return Value

A string containing the last element in Path.

Description

Returns the name of the last path component, less any extension.

Rules at a Glance

The file extension of the last element in Path isn't included in the returned string.

Programming Tips and Gotchas

  • GetBaseName doesn't verify that a given file or folder exists in Path.
  • In stripping the "file extension" and returning the base name of Path, GetBaseName has no intelligence. That is, it doesn't know whether the last component of Path is a path or a filename. If the last component includes one or more dots, it simply removes the last one, along with any following text. Hence, GetBaseName returns a null string for a Path of (.) and it returns (.) for a Path of (..). It is, in other words, really a string manipulation function, rather than a file function.

See Also

FileSystemObject.GetExtensionName Method

FileSystemObject.GetDrive Method  

Syntax

oFileSysObj.GetDrive(drivespecifier)

oFileSysObj

Use: Required

Data Type: FileSystemObject object

A FileSystemObject object.

drivespecifier

Use: Required

Data Type: String

A drive name, share name, or network path.

Return Value

A Drive object.

Description

Obtains a reference to a Drive object for the specified drive.

Rules at a Glance

  • If drivespecifier is a local drive or the letter of a mapped drive, it can consist of only the drive letter (e.g., "C"), the drive letter with a colon ("C:"), or the drive letter and path to the root directory (e.g., "C:") without generating a runtime error.
  • If drivespecifier is a share name or network path, GetDrive ensures that it exists as part of the process of creating the Drive object; if it doesn't, the method generates runtime error 76, "Path not found."
  • If the specified drive isn't connected or doesn't exist, runtime error 67, "Device unavailable," occurs.

Programming Tips and Gotchas

  • Individual drive objects can be retrieved from the Drives collection by using the Drives property. This is most useful, though, if you want to enumerate the drives available on a system. In contrast, the GetDrive method provides direct access to a particular Drive object.
  • If you are deriving the drivespecifier string from a path, you should first use GetAbsolutePathName to insure that a drive is present as part of the path. Then you should use FolderExists to verify that the path is valid before calling GetDriveName to extract the drive from the fully qualified path. For example:

    Dim oFileSys, oDrive
    
    Set oFileSys = CreateObject("Scripting.FileSystemObject")
    sPath = oFileSys.GetAbsolutePathName(sPath)
    If oFileSys.FolderExists(sPath) Then
     Set oDrive = oFileSys.GetDrive(oFileSys.GetDriveName(sPath))
    End If
  • If drivespecifier is a network drive or share, you should use the DriveExists method to confirm the required drive is available prior to calling the GetDrive method.
  • You must use the Set statement to assign the Drive object to a local object variable.

See Also

Drives Collection Object

FileSystemObject.GetDriveName Method  

Syntax

oFileSysObj.GetDriveName (Path)

oFileSysObj

Use: Required

Data Type: FileSystemObject object

A FileSystemObject object.

Path

Use: Required

Data Type: String

A path specifier.

Return Value

A String.

Description

Returns the drive name of a given path.

Rules at a Glance

If the drive name can't be determined from the given path, a zero-length string (" ") is returned.

Programming Tips and Gotchas

  • For local and mapped drives, GetDriveName appears to look for the colon as a part of the drive's name to determine whether a drive name is present. For network drives, it appears to look for the computer name and drive name.
  • GetDriveName is really a string-parsing method rather than a filesystem method. In particular, it does not verify that the drive name that it extracts from Path actually exists on the system.
  • Path can be a network drive or share.
FileSystemObject.GetExtensionName Method  

Syntax

oFileSysObj.GetExtensionName(Path)

oFileSysObj

Use: Required

Data Type: FileSystemObject object

A FileSystemObject object.

Path

Use: Required

Data Type: String

A path specifier.

Return Value

A String.

Description

Returns the extension of the file element of a given path.

Rules at a Glance

If the extension in Path can't be determined, a zero-length string (" ") is returned.

Programming Tips and Gotchas

  • GetExtensionName is a string parsing method rather than a filesystem method. It does not verify that Path is valid, does not verify that the filename designated in Path exists, and does not even guarantee that the value it returns is a valid file extension. In other words, GetExtensionName has no intelligence. It simply parses a string and returns the text that follows the last dot of the last element.
  • Path can be a network drive or share.

See Also

FileSystemObject.GetBaseName Method

FileSystemObject.GetFile Method  

Syntax

oFileSysObj.GetFile(FilePath)

oFileSysObj

Use: Required

Data Type: FileSystemObject object

A FileSystemObject object.

FilePath

Use: Required

Data Type: String

A path and filename.

Return Value

File object.

Description

Returns a reference to a File object.

Rules at a Glance

  • FilePath can be an absolute or a relative path.
  • If FilePath is a share name or network path, GetFile ensures that the drive or share exists as part of the process of creating the File object.
  • If any part of the path in FilePath can't be contacted or doesn't exist, an error occurs.

Programming Tips and Gotchas

  • The object returned by GetFile is a File object, not a TextStream object. A File object isn't an open file; the point of the File object is to perform methods such as copying or moving files and interrogating a file's properties. Although you can't write to or read from a File object, you can use the File object's OpenAsTextStream method to obtain a TextStream object. You can also save yourself a step by calling the FileSystemObject object's OpenTextFile method.
  • You should first use GetAbsolutePathName to create the required FilePath string.
  • If FilePath includes a network drive or share, you could use the DriveExists method to confirm that the required drive is available prior to calling the GetFile method.
  • Since GetFile generates an error if the file designated in FilePath doesn't exist, you should call the FileExists method before calling GetFile.
  • You must use the Set statement to assign the File object reference to a local object variable.

See Also

FileSystemObject.GetFolder Method, FileSystemObject.GetDrive Method, FileSystemObject.OpenTextFile Method

FileSystemObject.GetFileName Method  

Syntax

oFileSysObj.GetFileName(Path)

oFileSysObj

Use: Required

Data Type: FileSystemObject object

A FileSystemObject object.

Path

Use: Required

Data Type: String

A path specifier.

Return Value

A String.

Description

Returns the filename element of a given path.

Rules at a Glance

  • If the filename can't be determined from the given Path, a zero-length string (" ") is returned.
  • Path can be a relative or absolute reference.

Programming Tips and Gotchas

  • GetFileName doesn't verify that a given file exists in Path.
  • Path can be a network drive or share.
  • Like all the Getx Name methods of the FileSystemObject object, the GetFileName method is more a string manipulation routine that an object-related routine. GetFileName has no built-in intelligence (and, in fact, seems to have even less intelligence than usual for this set of methods); it simply assumes that the last element of the string that is not part of a drive and path specifier is in fact a filename. For example, if Path is C:Windows, the method returns the string "Windows"; if Path is C:Windows (which unambiguously denotes a folder rather than a filename), the method still returns the string "Windows."
FileSystemObject.GetFileVersion Method  

Syntax

oFileSysObj.GetFileVersion(FileName)

oFileSysObj

Use: Required

Data Type: FileSystemObject object

A reference to the FileSystemObject object.

FileName

Use: Required

Data Type: String

A path and filename.

Return Value

A String.

Description

Retrieves version information about the file specified in FileName.

Rules at a Glance

  • FileName should include the path as well as the name of the file. The path component can be either an absolute or a relative path to the file.
  • If path information is omitted, VBScript attempts to find FileName in the current folder.
  • This function reports version information in the format:

    Major_Version.Minor_Version.0.Build
  • If a file does not contain version information, the function returns an empty string (" ").

Programming Notes

  • The files that can contain version information are executable files (.exe) and dynamic link libraries (.dll).
  • If you're using VBScript to replace a private executable or DLL with another, be particularly careful with version checking, since it has been a particularly serious source of error. Ensuring that the new version of the file should be installed requires that any one of the following conditions be true:

    • It has the same major and minor version but a later build number than the existing file.
    • It has the same major version but a greater minor version number than the existing file.
    • It has a higher version number than the existing file.
  • It's also a good idea to copy the replaced file to a backup directory, such as the Windows Sysbckup directory.
  • If you're thinking of using VBScript to replace a system executable or DLL with another, it's best to use a professional installation program for this purpose.
  • Although this function is listed in the type library and is actually implemented in the Scripting Runtime, no documentation for it is available in the HTML Help file.

See Also

ScriptEngineBuildVersion Function, ScriptEngineMajorVersion Function, ScriptEngineMinorVersion Function

FileSystemObject.GetFolder Method  

Syntax

oFileSysObj.GetFolder(FolderPath)

oFileSysObj

Use: Required

Data Type: FileSystemObject object

A FileSystemObject object.

FolderPath

Use: Required

Data Type: String

A path to the required folder.

Return Value

A Folder object.

Description

Returns a reference to a Folder object.

Rules at a Glance

  • FolderPath can be an absolute or relative path.
  • If FolderPath is a share name or network path, GetFolder ensures that the drive or share exists as part of the process of returning the Folder object.
  • If any part of FolderPath doesn't exist, an error occurs.

Programming Tips and Gotchas

  • You should first use GetAbsolutePathName to create the required FolderPath string.
  • If FolderPath includes a network drive or share, you could use the DriveExists method to confirm the required drive is available prior to calling the GetFolder method.
  • Since GetFolder requires that FolderPath is the path to a valid folder, you should call the FolderExists method to verify that FolderPath exists.
  • The GetFolder method allows you to directly obtain an object reference to a particular folder. You can also use the Item property of the Folders collection object for cases in which you must navigate the filesystem to reach a particular folder, or for those cases in which you're interested in enumerating the subfolders belonging to a particular folder.
  • You must use the Set statement to assign the Folder object reference to a local object variable.

See Also

Folders Collection Object

FileSystemObject.GetParentFolderName Method  

Syntax

oFileSysObj.GetParentFolderName(Path)

oFileSysObj

Use: Required

Data Type: FileSystemObject object

A FileSystemObject object.

Path

Use: Required

Data Type: String

A path specifier.

Return Value

A String.

Description

Returns the folder name immediately preceding the last element of a given path. In other words, if Path ends in a filename, the method returns the path to the folder containing that file. If Path ends in a folder name, the method returns the path to that folder's parent.

Rules at a Glance

  • If the parent folder name can't be determined from Path, a zero-length string (" ") is returned.
  • Path can be a relative or absolute reference.

Programming Tips and Gotchas

  • GetParentFolderName doesn't verify that any element of Path exists.
  • Path can be a network drive or share.
  • GetParentFolderName assumes that the last element of the string that isn't part of a drive specifier is the parent folder. It makes no other check than this. As with all the Getx Name methods of the FileSystemObject object, the GetParentFolderName method is more a string parsing and manipulation routine than an object-related routine.
FileSystemObject.GetSpecialFolder Method  

Syntax

oFileSysObj.GetSpecialFolder(SpecialFolder)

oFileSysObj

Use: Required

Data Type: FileSystemObject object

A FileSystemObject object.

SpecialFolder

Use: Required

Data Type: Special folder constant

A value specifying one of three special system folders.

Return Value

A Folder object.

Description

Returns a reference to a Folder object of one of the three special system folders: System, Temporary, and Windows.

Rules at a Glance

SpecialFolder can be one of the following special folder constants:

Constant

Value

Description

SystemFolder

1

The Windows system folder (/windows/system or /windows/system32)

TemporaryFolder

2

The folder that stores temporary files (../windows/temp)

WindowsFolder

0

The root folder of the Windows system folder tree (/windows or /winnt)

Programming Tips and Gotchas

  • As the previous table shows, the Scripting Runtime type library defines constants of the SpecialFolderConst enumeration that can be used in place of their numeric equivalents. You can use them in your scripts in either of two ways. You can define the constants yourself by adding the following code to your script:

    Const WindowsFolder = 0
    Const SystemFolder = 1
    Const TemporaryFolder = 2

    You can also include a METADATA tag in an ASP global.asa file or include the following line in a Windows Script Host (.wsf ) file in order to access the constants from the Scripting Runtime type library:

    
     
  • Prior to the development of the Scripting Runtime Library with its support for the FileSystemObject, the only way to determine the location of system folders was via the Win32 API. This is a much simpler way of getting at that information. This is especially significant when using VBScript with the Windows Script Host, and adds an extremely powerful aspect to writing administrative or maintenance scripts with VBScript.
  • You can use the Set statement to assign the Folder object reference to a local object variable. However, if you're interested only in retrieving the path to the special folder, you can do it with a statement like the following:

    sPath = oFileSys.GetSpecialFolder(iFolderConst)

    or:

    sPath = oFileSys.GetSpecialFolder(iFolderConst).Path

    The first statement works because the Path property is the Folder object's default property. Since the assignment isn't to an object variable, it's the default property's value, rather than the object reference, that is assigned to sPath.

  • WSH includes a SpecialFolders collection. However, it does not duplicate the functionality of the GetSpecialFolder method.
FileSystemObject.GetStandardStream Method  

Syntax

oFileSys.GetStandardStream(StandardStreamType, [Unicode]) 

oFileSys

Use: Required

Data Type: FileSystemObject object

A reference to the FileSystemObject object.

StandardStreamType

Use: Required

Data Type: Long

A constant indicating which standard stream (input, output, or error) should be returned by the function.

Unicode

Use: Optional

Data Type: Boolean

A Boolean indicating whether the stream should be Unicode or ASCII.

Return Value

A TextStream object.

Description

Allows you to read from the standard input stream and write to the standard output or standard error streams.

Rules at a Glance

  • StandardStreamType can be one of the following constants defined in the Scripting Runtime type library:

Constant

Value

Description

StdIn

0

Standard input

StdOut

1

Standard output

StdErr

2

Standard error

  • The Scripting Runtime type library defines constants of the StandardStreamTypes enumeration that can be used in place of their numeric equivalents for the StandardStreamType argument. You can use them in your scripts in either of two ways. You can define the constants yourself by adding the following code to your script:

    Const StdIn = 0
    Const StdOut = 1
    Const StdErr = 2

    You can also include an ASP METADATA tag in the global.asa file or the following line in a Windows Script Host (.wsf ) file in order to access the constants from the Scripting Runtime type library:

    
     
  • The Unicode parameter can be either Unicode (True) or ASCII (False).

Programming Tips and Gotchas

  • The GetStandardStream method is available from a WSH script run in console mode using CScript.exe as the WSH engine. Otherwise, attempting to retrieve a reference to the TextStream object returned by the method generates an "Invalid handle" or (in ASP) a "Server.CreateObject failed" error message.
  • Note that standard input is a read-only stream, while standard output and standard error are write-only streams.
  • Although the function is implemented in the Scripting Runtime library, it is currently undocumented.
  • This method is functionally equivalent to three methods in the WSH object model: the WScript.StdIn property, which returns a TextStream object representing the standard input; the WScript.StdOut property, which returns a TextStream object representing the standard output; the WScript.StdErr property, which returns a TextStream object representing the standard error stream.

See Also

TextStream Object

FileSystemObject.GetTempName Method  

Syntax

oFileSysObj.GetTempName 

oFileSysObj

Use: Required

Data Type: FileSystemObject object

A FileSystemObject object.

Return Value

A String.

Description

Returns a system-generated temporary file or folder name.

Rules at a Glance

GetTempName doesn't create a temporary file or folder; it simply provides a name you can use with the CreateTextFile method.

Programming Tips and Gotchas

  • As a general rule, you shouldn't create your own temporary filenames. Windows provides an algorithm within the Windows API to generate the special temporary file and folder names so that it can recognize them later.
  • If you are calling GetTempName as the first step in creating a temporary file, you can also call the GetSpecialFolder method to retrieve the path of the temporary directory, as follows:

    Const TemporaryFolder = 2
    Dim oFS, sTempPath
    Set oFS = CreateObject("Scripting.FileSystemObject")
    sTempPath = oFS.GetSpecialFolder(TemporaryFolder)

    You can then form the complete path to the temporary folder as follows:

    sFullPath = sTempPath & "' & sTempFileName
FileSystemObject.MoveFile Method  

Syntax

oFileSysObj.MoveFile source, destination

oFileSysObj

Use: Required

Data Type: FileSystemObject object

A FileSystemObject object.

source

Use: Required

Data Type: String

The path to the file or files to be moved.

destination

Use: Required

Data Type: String

The path to the location where the file or files are to be moved.

Description

Moves a file from one folder to another.

Rules at a Glance

  • If source contains wildcard characters or if destination ends in a path separator, destination is interpreted as a path; otherwise, its last component is interpreted as a filename.
  • If the destination file exists, an error occurs.
  • source can contain wildcard characters, but only in its last component. This allows multiple files to be moved.
  • destination can't contain wildcard characters.
  • Both source and destination can be either absolute or relative paths.
  • Both source and destination can be network paths or share names.

Programming Tips and Gotchas

  • MoveFile resolves both arguments before beginning the operation.
  • Any single file move operation is atomic; that is, any file removed from source is copied to destination. However, if an error occurs while multiple files are being moved, the execution of the function terminates, but files already moved aren't moved back to their previous folder. If a fatal system error occurs during the execution of this method (like a power failure), the worst that can happen is that the affected file is copied to the destination but not removed from the source. There are no rollback capabilities built into the File.Move method, since, because the copy part of this two-stage process is executed first, the file can't be lost. But while there is no chance of losing data, particularly in multifile operations, it's more difficult to determine whether the move operations have succeeded. This is because an error at any time while files are being moved causes the MoveFile method to be aborted.
  • You can use the GetAbsolutePath, FolderExists, and FileExists methods prior to calling the MoveFile method to ensure its success.
  • The MoveFile method differs from the File object's Move method by allowing you to directly designate a file to be moved rather than requiring that you first obtain an object reference to it. It also allows you to move multiple files rather than the single file represented by the File object.

See Also

FileSystemObject.CopyFile Method, FileSystemObject.FileExists Method, FileSystemObject.GetAbsolutePathName Method

FileSystemObject.MoveFolder Method  

Syntax

oFileSysObj.MoveFolder source, destination

oFileSysObj

Use: Required

Data Type: FileSystemObject object

A FileSystemObject object.

source

Use: Required

Data Type: String

The path to the folder or folders to be moved.

destination

Use: Required

Data Type: String

The path to the location where the folder or folders are to be moved.

Description

Moves a folder along with its files and subfolders from one location to another.

Rules at a Glance

  • source must end with either a wildcard character or no path separator.
  • Wildcard characters can be used in source, but only for the last component.
  • Wildcard characters can't be used in destination.
  • All subfolders and files contained within the source folder are copied to destination unless disallowed by the wildcard characters. That is, the MoveFolder method is recursive.
  • If destination ends with a path separator or Source ends with a wildcard, MoveFolder assumes the folder in Source exists in Destination. For example:

    C:
     Rootone
     SubFolder1
     SubFolder2
     RootTwo

    The command MoveFolder "c:Rootone*", "C:RootTwo" produces this folder structure:

    C:
     Rootone
     RootTwo
     SubFolder1
     SubFolder2

    The command MoveFolder "c:Rootone", "C:RootTwo" produces this folder structure:

    C:
     RootTwo
     Rootone
     SubFolder1
     SubFolder2
  • source and destination can be either absolute or relative paths.
  • source and destination can be network paths or share names.

Programming Tips and Gotchas

  • MoveFolder resolves both arguments before starting the operation.
  • If a fatal system error occurs during the execution of this method (like a power failure), the worst that can happen is that the file is copied to the destination but not removed from the source. There are no rollback capabilities built into the FileSystemObject.MoveFolder method, since, because the copy part of this two-stage process is executed first, the file can't be lost.
  • Although there is no chance of actually losing data, it can be difficult to determine whether the operation has succeeded or failed in the event of an error when multiple folders are being moved. This is because an error in the middle of a multifile move operation causes the MoveFolder method to be abandoned and subsequent folder operations to be aborted.
  • You can call the GetAbsolutePath and FolderExists methods before calling the MoveFile method to ensure its success.
  • If the user has adequate rights, the source or destination can be a network path or share name. For example:

    MoveFolder "c:Rootone", "\NTSERV1d$RootTwo"

See Also

FileSystemObject.CopyFile Method, FileSystemObject.FolderExists Method, FileSystemObject.GetAbsolutePathName Method

FileSystemObject.OpenTextFile Method  

Syntax

oFileSysObj.OpenTextFile(FileName[, IOMode[, Create[, Format]]])

oFileSysObj

Use: Required

Data Type: FileSystemObject object

A FileSystemObject object.

FileName

Use: Required

Data Type: String

The path and filename of the file to open.

IOMode

Use: Optional

Data Type: Long

A constant specifying the purpose for opening the file.

Create

Use: Optional

Data Type: Boolean

A Boolean flag denoting whether the file should be created if it can't be found in the given path.

Format

Use: Optional

Data Type: Long

A constant specifying ASCII or Unicode format.

Return Value

A TextStream object.

Description

Opens (and optionally first creates) a text file for reading or writing.

Rules at a Glance

  • File open (IOMode) values are:

Constant

Value

Description

ForAppending

8

Opens the file for appending; that is, the current contents of the file are protected and new data written to the file is placed at the end of the file.

ForReading

1

Opens the file for reading; ForReading files are read-only.

ForWriting

2

Opens the file for writing; all previous file content is overwritten by new data.

  • Tristate (Format) values are:

Constant

Value

Description

TristateUseDefault

-2

Opens as System default

TristateTrue

-1

Opens as Unicode

TristateFalse

0

Opens as ASCII

  • The path element of FileName can be relative or absolute.
  • The default IOMode setting is ForReading (1).
  • The default Format setting is ASCII (False).
  • If another process has opened the file, the method fails with a "Permission Denied" error.

Programming Tips and Gotchas

  • You can use the GetAbsolutePath and FileExists methods prior to calling the OpenTextFile method to ensure its success.
  • As the table listing values for the IOMode parameter shows, the Scripting Runtime type library defines constants of the IOMode enumeration that can be used in place of their numeric equivalents. You can use them in your scripts in either of two ways. You can define the constants yourself by adding the following code to your script:

    Const ForReading = 1
    Const ForWriting = 2
    Const ForAppending = 8

    You can also include a METADATA tag in the ASP global.asa file or the following line in a Windows Script Host (.wsf ) file in order to access the constants from the Scripting Runtime type library:

    
     
  • The value of IOMode can be only that of a single constant. For example, a method call such as the following:

    lMode = ForReading Or ForWriting
    oFileSys.OpenTextStream(strFileName, lMode) ' WRONG
    generates runtime error 5, "Invalid procedure call or argument."
  • As the table listing values for the Format parameter shows, the Scripting Runtime type library defines constants of the Tristate enumeration that can be used in place of their numeric equivalents. You can use them in your scripts in either of two ways. You can define the constants yourself by adding the following code to your script:

    Const TristateFalse = 0
    Const TristateTrue = -1
    Const TristateUseDefault = -2

    You can also include a METADATA tag in the ASP global.asa file or the following line in a Windows Script Host (.wsf ) file in order to access the constants from the Scripting Runtime type library:

    
     
  • If the user has adequate rights, the path element of FileName can be a network path or share name. For example:

    OpenTextFile "\NTSERV1d$RootTwomyFile.txt"

See Also

File.OpenAsTextStream Method, TextStream Object

Filter Function  

Syntax

Filter(SourceArray, FilterString[, Switch[, Compare]])

SourceArray

Use: Required

Data Type: String or numeric

An array containing values to be filtered.

FilterString

Use: Required

Data Type: String or numeric

The string of characters to find in the source array.

Switch

Use: Optional

Data Type: Boolean

A Boolean (True or False) value. If True, the default value, Filter includes all matching values in result; if False, Filter excludes all matching values (or, to put it another way, includes all nonmatching values).

Compare

Use: Optional

Data Type: Long

An optional constant (possible values are 0, vbBinaryCompare; 1, vbTextCompare) that indicates the type of string comparison to use. The default value is 0, vbBinaryCompare.

Return Value

A String array of the elements filtered from SourceArray.

Description

Produces an array of matching values from an array of source values that either match or don't match a given filter string. In other words, individual elements are copied from a source array to a target array if they either match or don't match a filter string.

Rules at a Glance

  • The default Switch value is True.
  • The default Compare value is 0, vbBinaryCompare.
  • vbBinaryCompare is case-sensitive; that is, Filter matches both character and case. In contrast, vbTextCompare is case-insensitive, matching only character regardless of case.

Programming Tips and Gotchas

  • SourceArray elements that are Empty or that contain zero-length strings ("") are ignored by the Filter function.
  • The array you declare to assign the return value of Filter should be a simple variant, as the following code fragment illustrates:

    Dim aResult
    aResult = Filter(sNames, sCriteria, True)
  • Although the Filter function is primarily a string function, you can also filter numeric values. To do this, populate a SourceArray with numeric values. Although FilterString appears to be declared internally as a variant string, a Long or Integer can be passed to the function. For example:

    Dim varSource As Variant, varResult As Variant
    Dim strMatch As String
    
    strMatch = CStr(2)
    varSource = Array(10, 20, 30, 21, 22, 32)
    varResult = Filter(varSource, strMatch, True, _
     vbBinaryCompare)

    In this case, the resulting array contains four elements: 20, 21, 22, and 32.

  • The Filter function is an ideal companion to the Dictionary object. The Dictionary object is a collection-like array of values, each of which is stored with a unique string key. The Keys method of the Dictionary object allows you to produce an array of these Key values, which you can then pass into the Filter function as a rapid method of filtering the members of your Dictionary, as the following example demonstrates.

Example

 Dim sKeys 
 Dim sFiltered 
 Dim sMatch 
 Dim blnSwitch 
 Dim oDict 
 
 Set oDict = CreateObject("Scripting.Dictionary")

 oDict.Add "Microsoft", "One Microsoft Way"
 oDict.Add "AnyMicro Inc", "31 Harbour Drive"
 oDict.Add "Landbor Data", "The Plaza"
 oDict.Add "Micron Co.", "999 Pleasant View" 

 sKeys = oDict.Keys
 sMatch = "micro"
 blnSwitch = True
 'find all keys that contain the string "micro" - any case
 sFiltered = Filter(sKeys, sMatch, blnSwitch, _
 vbTextCompare)
 'now iterate through the resulting array
 For i = 0 To UBound(sFiltered)
 sMsg = sMsg & sFiltered(i) & ", " & oDict.Item(sFiltered(i)) & _
 vbCrLf
 Next 
 MsgBox sMsg

See Also

RegExp Object

Fix Function  

Syntax

Fix(number)

number

Use: Required

Data Type: Numeric

Any valid numeric expression.

Return Value

The same data type as passed to the function containing only the integer portion of number.

Description

Removes the fractional part of a number. Operates in a similar way to the Int function.

Rules at a Glance

  • If number is Null, Fix returns Null.
  • The operations of Int and Fix are identical when dealing with positive numbers: numbers are rounded down to the next lowest whole number. For example, both Int(3.14) and Fix(3.14) return 3.
  • If number is negative, Fix removes its fractional part, thereby returning the next greater whole number. For example, Fix(-3.667) returns -3. This contrasts with Int, which returns the negative integer less than or equal to number (or -4, in the case of our example).

Example

 Dim dblTest
 Dim varTest

 dblTest = -100.9353
 varTest = Fix(dblTest)
 ' returns -100
 Msgbox varTest & " " & TypeName(varTest) 

 dblTest = 100.9353
 varTest = Fix(dblTest)
 'returns 100
 Msgbox.Print varTest & " " & TypeName(varTest) 

Programming Tips and Gotchas

Fix doesn't round number to the nearest whole number; it simply removes the fractional part of number. Therefore, the integer returned by Fix is the nearest whole number less than (or greater than, if the number is negative) the number passed to the function.

See Also

Int Function, CInt Function, CLng Function, Round Function

Folder Object  

Createable

No

Returned by

Drive.RootFolder property

FileSystemObject.CreateFolder method

FileSystemObject.GetFolder method

Folder.SubFolders.Item property

Folders.Add method

Library

Microsoft Scripting Runtime

Description

The Folder object allows you to interrogate the system properties of the folder and provides methods that allow you to copy, move, and delete the folder. You can also create a new text file within the folder.

The Folder object is unusual because with it, you can gain access to a Folders collection object. The more usual method is to extract a member of a collection to gain access to the individual object. However, because the Drive object exposes only a Folder object for the root folder, you have to extract a Folders collection object from a Folder object (the collection represents the subfolders of the root). From this collection, you can navigate downward through the filesystem to extract other Folder objects and other Folders collections. A Boolean property, IsRootFolder, informs you of whether the Folder object you are dealing with currently is the root of the drive.

The Folder object is one of the objects in the Filesystem object model; for an overview of the model, see the "File System Object Model" entry.

Properties

Attributes

Data Type: Long

A set of flags representing the folder's attributes. The flags that apply to folders are:

Constant

Value

Archive

32

Directory

16

Hidden

2

ReadOnly

1

System

4

As the table shows, the Scripting Runtime type library defines constants of the FileAttribute enumeration that can be used in place of their numeric equivalents. You can use them in your scripts in either of two ways. You can define the constants yourself by adding the following code to your script:

Const Normal = 0
Const ReadOnly = 1
Const Hidden = 2
Const System = 4
Const Directory = 16
Const Archive = 32

Or you can take advantage of the host's facilities to make the constants accessible. In Active Server Pages, you can include the METADATA tag in the global.asa file and provide the type library identifier for the Scripting Runtime as follows:

In Windows Script Host, you can include the following line in a .wsf file in order to access the constants defined in the Scripting Runtime:


 

You can determine which flag is set by using a logical AND along with the value returned by the property and the value of the flag you'd like to test. For example:

If oFolder.Attributes And ReadOnly Then
 ' Folder is read-only

To clear a flag, And the value of the Attributes property with a Long in which the flag you want to clear is turned off. For example, the following code clears a Folder object's read-only flag:

oFile.Attributes = oFile.Attributes And (Not
ReadOnly)

Date Created

Data Type: Date

The date and time the folder was created.

DateLastAccessed

Data Type: Date

The date and, if it's available from the operating system, the time that the folder was last accessed.

DateLastModified

Data Type: Date

The date and time the folder was last modified.

Drive

Data Type: Drive object

Returns a Drive object representing the drive on which this folder resides; the property is read-only.

Files

Data Type: Files collection object

Returns a read-only Files collection object representing all files in the current folder.

IsRootFolder

Data Type: Boolean

Returns True if the folder is the root folder of its drive.

Name

Data Type: String

Returns the name of the folder.

ParentFolder

Data Type: Folder object

Returns a folder object representing the folder that's the parent of the current folder. It returns Nothing if the current object is the root folder of its drive (i.e., if its IsRootFolder property is True).

Path

Data Type: String

Returns the complete path of the current folder, including its drive. It is the default property of the Folder object.

ShortName

Data Type: String

Returns a DOS 8.3 folder name without the folder's path. The property is read-only.

ShortPath

Data Type: String

Returns the complete path to a folder in DOS 8.3 format. The property is read-only.

Size

Data Type: Long

Returns the total size of all files, subfolders, and their contents in the folder structure, starting with the current folder. The property is read-only.

In previous versions of the Scripting Runtime, this property failed to accurately report the size of a folder whose files and subfolders occupied more than 2 GB of disk space.

Attempting to retrieve the value of a Folder object's Size property when that folder is a drive's root folder (that is, its IsRootFolder property returns True) generates a runtime error.

SubFolders

Data Type: Folders collection object

Returns a Folders collection object representing all subfolders within the current folder.

Type

Data Type: String

Returns the description of a filesystem object, as recorded in the system registry. For Folder objects, the property always returns "File Folder."

Methods

Copy

Create TextFile

Delete

Move

Folder.Copy Method  

Syntax

oFolderObj.Copy Destination [, OverwriteFiles]

oFolderObj

Use: Required

Data Type: Folder object

A Folder object.

Destination

Use: Required

Data Type: String

The path and, optionally, the filename of the copy to be made.

OverwriteFiles

Use: Optional

Data Type: Boolean

Indicates whether existing files and folders should be overwritten (True) or not (False).

Description

Copies the current folder and its contents, including other folders, to another location.

Rules at a Glance

  • Wildcard characters can't be used in Destination.
  • The folder and all subfolders and files contained in the source folder are copied to Destination. That is, the Copy method is recursive.
  • Unlike the FileSystemObject.CopyFolder method, there is no operational difference between ending Destination with a path separator or not.

Programming Tips and Gotchas

  • If the destination path or any of the files contained in the Destination structure are set to read-only, the Copy method will fail regardless of the value of OverwriteFiles and will generate a "Permission denied" error.
  • If OverwriteFiles is set to False, and the source folder or any of the files contained in the Destination structure exists in the Destination structure, then trappable error 58, "File Already Exists," is generated.
  • If an error occurs while copying more than one file, the Copy method exits immediately, leaving the rest of the files uncopied. There is also no rollback facility to undo the copies prior to the error.
  • If the user has adequate rights, Destination can be a network path or share name. For example:

    oFolder.Copy "\NTSERV1d$RootTwo"
Folder.CreateTextFile Method  

Syntax

oFolderObj.CreateTextFile FileName[, Overwrite[, Unicode]])

oFolderObj

Use: Required

Data Type: Folder object

A Folder object.

FileName

Use: Required

Data Type: String

Any valid filename and optional path.

Overwrite

Use: Optional

Data Type: Boolean

Flag to indicate whether an existing file of the same name should be overwritten.

Unicode

Use: Optional

Data Type: Boolean

Flag to indicate whether file is to be written in Unicode or ASCII.

Return Value

A TextStream object.

Description

Creates a new file at the specified location and returns a TextStream object for that file.

Rules at a Glance

  • Filename can be a relative or absolute path. Wildcard characters are not allowed in FileName.
  • If no path is specified in Filename, the script's current drive and directory are used. If no drive is specified in Filename, the script's current drive is used.
  • The default value for Overwrite is False.
  • If Unicode is set to True, a Unicode file is created; otherwise it's created as an ASCII text file.
  • The default value for Unicode is False.

Programming Tips and Gotchas

  • If the path specified in Filename does not exist, the method fails. To prevent this error, you can use the FileSystemObject object's FolderExists method to be sure that the path is valid.
  • The newly created text file is automatically opened only for writing. If you subsequently wish to read from the file, you must first close it and reopen it in read mode.
  • If the file referred to in Filename already exists as a read-only file, the CreateTextFile method fails regardless of the value of Overwrite.
  • You must use the Set statement to assign the TextStream object to a local object variable.
  • If the user has adequate rights, Filename can contain a network path, or share name. For example:

    oFolder.CreateTextFile "\NTSERV1RootTestmyFile.doc"
  • The CreateTextFile method in the Folder object is identical in operation to that in the FileSystemObject object.

See Also

FileSystemObject.CreateTextFile Method, TextStream Object

Folder.Delete Method  

Syntax

oFolderObj.Delete [Force]

oFolderObj

Use: Required

Data Type: Folder object

A Folder object.

Force

Use: Optional

Data Type: Boolean

If set to True, any read-only flag on a file or a folder to be deleted is ignored and the file or folder is deleted. When set to False, a read-only flag prevents that folder or file from being deleted. Its default value is False.

Description

Removes the folder specified by the Folder object and all its files and subfolders.

Rules at a Glance

  • If any of the files within the folder are open, the method fails with a "Permission Denied" error.
  • The Delete method deletes all the contents of the given folder, including subfolders and their contents.
  • The default setting for Force is False. If any of the files in the folder or its subfolders are set to read-only, the method will fail.
  • If Force is set to False and any of the files in the folders are set to read-only, the method fails.

Programming Tips and Gotchas

  • The Delete method deletes a folder and its files and subfolders permanently; it does not move the folder or its files and subfolders to the Recycle Bin.
  • If an error occurs while deleting more than one file in the folder, the Delete method exits immediately, thereby leaving the rest of the folders or files undeleted. There is also no rollback facility to undo the deletions prior to the error.
  • Unlike the FileSystemObject's DeleteFolder method, which accepts wildcard characters in the path parameter and can therefore delete multiple folders, the Delete method deletes only the single folder represented by the Folder object.
  • Immediately after the Delete method executes, the Folder's collection object containing the Folder object is automatically updated. The deleted folder is removed from the collection, and the collection count is reduced by one. You shouldn't try to access the deleted Folder object again, and you should set the local object variable to Nothing, as the following code snippet demonstrates:

    Set ofsSubFolder = ofsSubFolders.Item("roottwo")
     MsgBox ofsSubFolders.Count
     ofsSubFolder.Delete False
     MsgBox ofsSubFolders.Count
    Set ofsSubFolder = Nothing

See Also

FileSystemObject.DeleteFile Method, FileSystemObject.DeleteFolder Method

Folder.Move Method  

Syntax

oFolderObj.Move destination

oFolderObj

Use: Required

Data Type: Folder object

A Folder object.

destination

Use: Required

Data Type: String

The path to the location where the folder or folders are to be moved.

Description

Moves a folder structure from one location to another.

Rules at a Glance

  • Wildcard characters can't be used in destination.
  • If any of the files within the folder being moved are open, an error is generated.
  • All subfolders and files contained within the source folder are copied to destination, unless disallowed by the wildcard characters. That is, the Move method is recursive.
  • destination can be either an absolute or a relative path.

Programming Tips and Gotchas

  • If a fatal system error (like a power failure) occurs during the execution of this method, the worst that can happen is that the folder is copied to the destination but not removed from the source. There are no rollback capabilities built into the Folder.Move method; since, the copy part of this two-stage process is executed first, the folder can't be lost.
  • If an error occurs in the middle of a move operation, the operation is terminated, and the remaining files and folders in the folder aren't moved.
  • If a folder or a file by the same name already exists in destination, the method generates runtime error 58, "File already exists." To prevent this, you can use the FileSystemObject's FolderExists and GetAbsolutePath methods prior to calling the Move method.
  • Unlike the FileSystemObject's MoveFolder method, which accepts wildcard characters in the source parameter and can therefore move multiple folders, the Move method moves only the single folder represented by the Folder object and its contents.
  • Immediately after the Move method executes, the Folders collection object containing the Folder object is automatically updated, the moved folder is removed from the collection, and the collection count is reduced by one. You shouldn't try to access the moved folder object again from the same Folders collection object.
  • oFolderObj, the Folder object reference, remains valid after the folder has been moved. Its relevant properties (the Drive, ParentFolder, Path, and ShortPath properties, for example) are all updated to reflect the folder's new path after the move.
  • If the user has adequate rights, the destination can be a network path or share name. For example:

    oFolder.Move "\NTSERV1d$RootTwo"

See Also

FileSystemObject.MoveFile Method, FileSystemObject.MoveFolder Method

Folders Collection Object  

Createable

No

Returned by

Folder.SubFolders property

Library

Microsoft Scripting Runtime

Description

The Folders collection object is a container for Folder objects. Normally, you'd expect to access a single object from the collection of that object; for example, you'd expect to access a Folder object from the Folders collection object. However, things are the other way around here: you access the Folders collection object from an instance of a Folder object. This is because the first Folder object you instantiate from the Drive object is a Root Folder object, and from it you instantiate a subfolders collection. You can then instantiate other Folder and subfolder objects to navigate through the drive's filesystem.

The Folders collection is a subfolder of any Folder object. For instance, the top-level Folders collection (representing all of the folders in the root directory of a particular drive) can be can be instantiated as follows:

Dim oFS, oFolders
Set oFS = CreateObject("Scripting.FileSystemObject")
Set oFolders = oFS.Drives("C").RootFolder.SubFolders 

The Folders collection object is one of the objects in the File System object model; see the File System object model entry for an overview of the model, including the library reference needed to access it.

Properties

Item

Data Type: Folder object

Retrieves a particular Folder object from the Folders collection object. You can access an individual folder object by providing the exact name of the folder without its path. However, you can't access the item using its ordinal number. For example, the following statement returns the Folder object that represents the roottwo folder:

Set ofsSubFolder = ofsSubFolders.Item("roottwo")

Count

Data Type: Long

The number of Folder objects contained in the Folders collection.

Methods

Add

See Also

Folders.Add Method, Folder Object

Folders.Add Method  

Syntax

oFoldersCollObj.Add newfoldername

oFoldersCollObj

Use: Required

Data Type: Folders collection object

Any object variable returning a Folders collection object.

newfoldername

Use: Required

Data Type: String

The name of the new folder.

Return Value

Folder object.

Description

Creates a new folder. The location of the new folder is determined by the parent to which the Folders collection object belongs. For example, if you are calling the Add method from a Folders collection object that is a child of the root Folder object, the new folder is created in the root (i.e., it's added to the root's subfolders collection). For example:

Dim oFileSys
Dim oRoot, oChild
Dim oRootFolders

Set oFileSys = CreateObject("Scripting.FileSystemObject")
Set oRoot = oFileSys.Drives("C").RootFolder
Set oRootFolders = oRoot.SubFolders
Set oChild = oRootFolders.Add("Downloads")

Rules at a Glance

You can't use a path specifier in newfoldername ; you can use only the name of the new folder.

See Also

FileSystemObject.CreateFolder Method

For . . . Next Statement  

Syntax

For counter = initial_value To maximum_value [Step stepcounter]
 code to execute on each iteration
 [Exit For]
Next

counter

Use: Required

Data Type: Numeric

A variable to be used as the loop counter.

initial_value

Use: Required

Data Type: Numeric

Any valid numeric expression that specifies the loop counter's initial value.

maximum_value

Use: Required

Data Type: Numeric

Any valid numeric expression that specifies the loop counter's maximum value.

stepcounter

Use: Optional (required if Step used)

Data Type: Numeric

Any valid numeric expression that indicates how much the loop counter should be incremented with each new iteration of the loop.

Description

Defines a loop that executes a given number of times, as determined by a loop counter. To use the For...Next loop, you must assign a numeric value to a counter variable. This counter is either incremented or decremented automatically with each iteration of the loop. In the For statement, you specify the value that is to be assigned to the counter initially and the maximum value the counter will reach for the block of code to be executed. The Next statement marks the end of the block of code that is to execute repeatedly, and also serves as a kind of flag that indicates the counter variable is to be modified.

Rules at a Glance

  • If initial_value is greater than maximum_value, and no Step keyword is used or the step counter is positive, the For...Next loop is ignored and execution commences with the first line of code immediately following the Next statement.
  • If initial_value and maximum_value are equal and stepcounter is 1, the loop executes once.
  • counter can't be a variable of type Boolean or an array element.
  • counter is incremented by one with each iteration unless the Step keyword is used.
  • If the Step keyword is used, stepcounter specifies the amount counter is incremented if stepcounter is positive or decremented if it's negative.
  • If the Step keyword is used, and stepcounter is negative, initial_value should be greater than maximum_value. If this isn't the case, the loop doesn't execute.
  • The For...Next loop can contain any number of Exit For statements. When the Exit For statement is executed, program execution commences with the first line of code immediately following the Next statement.

Example

This example demonstrates how to iterate from the end to the start of an array of values:

sArray=Array(10, 12, 14, 16, 18, 20, 22, 24)
For i = UBound(sArray) To LBound(sArray) Step -1
 total = total +sArray(i)
Next

This example demonstrates how to select only every other value from an array of values:

sArray=Array(10, 12, 14, 16, 18, 20, 22, 24)
For i = LBound(sArray) To UBound(sArray) Step 2
 total = total +sArray(i)
Next

Programming Tips and Gotchas

  • You can also nest For...Next loops:

    For iDay = 1 to 365
     For iHour = 1 to 23
     For iMinute = 1 to 59
     ...
     Next
     Next
    Next
  • You should avoid changing the value of counter in the code within the loop. Not only can this lead to unexpected results, but it also makes for code that's incredibly difficult to read and to understand.

See Also

For Each . . . Next Statement

For Each . . . Next Statement  

Syntax

For Each element In group
[statements]
[Exit For]
[statements]
Next

element

Use: Required

Data Type: Variant

A variable to which the current element from the group is assigned.

group

Use: Required

A collection or an array.

statements

Use: Optional

A line or lines of program code to execute within the loop.

Description

Loops through the items of a collection or the elements of an array.

Rules at a Glance

  • The For...Each code block is executed only if group contains at least one element.
  • All statements are executed for each element in group in turn until either there are no more elements in group, or the loop is exited prematurely using the Exit For statement. Program execution then continues with the line of code following Next.
  • For Each...Next loops can be nested, but each element must be unique. For example:

    For Each myObj In anObject
     For Each subObject In myObject
     sName(ctr) = subObject.NameProperty
     ctr = ctr + 1
     Next
    Next

    uses a nested For Each...Next loop, but two different variables, myObj and subObject, represent element.

  • Any number of Exit For statements can be placed with the For Each...Next loop to allow for conditional exit of the loop prematurely. On exiting the loop, execution of the program continues with the line immediately following the Next statement. For example, the following loop terminates once the program finds a name in the myObj collection that has fewer than 10 characters:

    For Each subObject In myObj
     SName = subObject.NameProperty
     If Len(Sname) < 10 then
     Exit For
     End if
    Next

Programming Tips and Gotchas

  • Each time the loop executes when iterating the objects in a collection, an implicit Set statement is executed. The following code reflects the "longhand" method that is useful for explaining what is actually happening during each iteration of the For Each...Next loop:

    For i = 1 to MyObject.Count
     Set myObjVar = MyObject.Item(i)
     MsgBox myObjVar.Name
    Next
  • Because the elements of an array are assigned to element by value, element is a local copy of the array element and not a reference to the array element itself. This means that you can't make changes to the array element using For Each...Next and expect them to be reflected in the array once the For Each...Next loop terminates, as demonstrated in the example shown next.

    Dim strNameArray(1)
    Dim intCtr
    
    strNameArray(0) = "Paul"
    strNameArray(1) = "Bill"
    
    intCtr = 0
    
    For Each varName In strNameArray
     varName = "Changed"
     Msgbox strNameArray(intCtr)
    intCtr = intCtr + 1
    Next

    For example, on the first iteration of the loop, although varName has been changed from "Paul" to "Changed," the underlying array element, strNameArray(0), still reports a value of "Paul." This proves that a referential link between the underlying array and object variable isn't present; instead, the value of the array element is passed to element by value.

See Also

Exit Statement, For . . . Next Statement

FormatCurrency, FormatNumber, FormatPercent Functions  

Syntax

FormatCurrency(number[,DecimalPlaces ][, _
  IncLeadingZero[,UseParenthesis[,GroupDigits]]]]) 
FormatNumber(number[,DecimalPlaces ][, _
 IncLeadingZero[,UseParenthesis[,GroupDigits]]]]) 
FormatPercent(number[,DecimalPlaces ][, _
 IncLeadingZero[,UseParenthesis[,GroupDigits]]]]) 

number

Use: Required

Data Type: Any numeric expression

The number to be formatted.

DecimalPlaces

Use: Optional

Data Type: Long

Number of digits the formatted string should contain after the decimal point.

IncLeadingZero

Use: Optional

Data Type: Long

Indicates whether the formatted string is to have a 0 before floating-point numbers between 1 and -1.

UseParenthesis

Use: Optional

Data Type: Long

Specifies whether parentheses should be placed around negative numbers.

GroupDigits

Use: Optional

Data Type: Long

Determines whether digits in the returned string should be grouped using the delimiter specified in the computer's regional settings. For example, on American English systems, the value 1000000 is returned as 1,000,000 if GroupDigits is True.

Return Value

String

Description

The three functions are almost identical. They all take identical arguments. The only difference is that FormatCurrency returns a formatted number beginning with the currency symbol specified in the computer's regional settings, while FormatNumber returns just the formatted number, and FormatPercent returns the formatted number followed by a percentage sign (%).

Rules at a Glance

  • If DecimalPlaces isn't specified, the value in the computer's regional settings is used.
  • Possible values for the IncLeadingZero, UseParenthesis, and GroupDigits parameters are -1, TristateTrue; 0, TristateFalse; and -2, TriStateUseDefault. You can define the constants in your scripts by using the VBScript Const statement as follows:

    Const TristateTrue = -1
    Const TristateFalse = 0
    Const TristateUseDefault = -2

    If you're using the constants in a WSH script, you could also include the following line in a Windows Script Host (.wsf ) file in order to access the constants from the Scripting Runtime type library:

    
     

    To access the constants in the ASP page, you can add the following METADATA tag to the application's global.asa file:

Programming Tips and Gotchas

These three functions first appeared in VBScript Version 2 as "light" alternatives to the VBA Format function. They are quick and easy to use, and make your code more self-documenting; you can instantly see what format is being applied to a number without having to decipher the format string.

FormatDateTime Function  

Syntax

FormatDateTime(date[,format])

date

Use: Required

Data Type: Date or String

Any expression that can be evaluated as a date.

format

Use: Optional

Data Type: Long

Defines the format; see the list of values in "Rules at a Glance."

Return Value

String

Description

Formats a date or time expression based on the computer's regional settings.

Rules at a Glance

  • The intrinsic constants to use for the format argument are:

    vbGeneralDate

    Value: 0

    Displays a date and/or time. If there is a date part, displays it as a short date. If there is a time part, displays it as a long time. If present, both parts are displayed. For example:

     MsgBox FormatDate Time(#04/10/03#, vbGeneralDate)

    displays 4/10/2003.

    VbLongDate

    Value: 1

    Uses the long date format specified in the client computer's regional settings. For example:

    MsgBox FormatDate Time(#04/10/03#, vbLongDate)

    displays Thursday, April 10, 2003.

    VbShortDate

    Value: 2

    Uses the short date format specified in the client computer's regional settings. For example:

    MsgBox FormatDate Time(#04/10/03#, vbShortDate)

    displays 4/102003.

    VbLongTime

    Value: 3

    Uses the time format specified in the computer's regional settings. For example:

    MsgBox FormatDate Time(#1:03:00 PM#, vbLong Time)

    displays 1:03:00 PM.

    VbShortTime

    Value: 4

    Uses a 24-hour format (hh:mm). For example:

    MsgBox FormatDate Time(#1:03:00 PM#, vbShortTime)

    displays 13:03.

  • The default date format is vbGeneralDate(0).
  • These constants are all defined in the VBScript library and hence are an intrinsic part of the language.

Programming Tips and Gotchas

Remember that date and time formats obtained from the client computer are based on the client computer's regional settings. It's not uncommon for a single application to be used internationally, so that date formats can vary widely. Not only that, but you can never be sure that a user has not modified the regional settings on a computer. In short, never take a date coming in from a client machine for granted; ideally, you should always insure it's in the format you need prior to using it.

Function Statement  

Syntax

[Public [Default] | Private] Function name [(arglist)] [( )] 
 [statements]
 [name = expression]
 [Exit Function] 
 [statements]
 [name = expression]
End Function

Public

Use: Optional

Type: Keyword

Indicates that the function is accessible in all scripts. If used in a class, indicates that the function is a member of the class's public interface. Public and Private are mutually exclusive; Public is the default.

Default

Use: Optional

Type: Keyword

Defines a method as the default member of a class. It is valid only for a public function defined within a Class...End Class statement. Only one property or method in a class block can be defined as the default member of the class.

Private

Use: Optional

Type: Keyword

Restricts access to the function to other procedures in the script where it is declared. If the function is a member of a class, it makes the function accessible only to other procedures in that class.

name

Use: Required

The name of the function.

arglist uses the following syntax and parts:

Use: Optional

A comma-delimited list of variables to be passed to the function as arguments from the calling procedure.

statements

Use: Optional

Program code to be executed within the function.

expression

Use: Optional

The value to return from the function to the calling procedure.

arglist uses the following syntax and parts:

[ByVal | ByRef] varname[( )]

ByVal

Use: Optional

Type: Keyword

The argument is passed by value; that is, the local copy of the variable is assigned the value of the argument.

ByRef

Use: Optional

Type: Keyword

The argument is passed by reference; that is, the local variable is simply a reference to the argument being passed. All changes made to the local variable are also reflected in the calling argument. ByRef is the default method of passing variables.

varname

Use: Required

The name of the local variable containing either the reference or value of the argument.

Description

Defines a function procedure.

Rules at a Glance

  • If you don't include either Public or Private keywords, a function is Public by default.
  • Any number of Exit Function statements can be placed within the function. After an Exit Function statement, execution continues on the line of code from which the function was called. For example, in the code:

    var = AddOne (AddTwo(x))

    an Exit Function statement in the AddTwo function causes execution to return to the line of code calling the function, so that the AddOne function is called next. If a value has not been assigned to the function when the Exit Function statement executes, the function will return Empty.

  • The return value of a function is passed back to the calling procedure by assigning a value to the function name. This may be done more than once within the function.
  • To return an object reference from a function, the object must be assigned to the function's return value using the Set statement. For example:

    Set x = GetAnObject ( )
    
    Function GetAnObject ( )
     Dim oTempObject
     Set oTempObject = New SomeObject
     oTempObject.Name = "Jane Doe"
     Set GetAnObject = oTempObject
    End Function
  • VBScript allows you to return arrays of any type from a procedure. Here's a quick example showing this in operation. Here, the PopulateArray function is called and is passed a string value. PopulateArray takes this value and concatenates the number 0 to 10 to it, assigns each value to an element of an array, then passes this array back to the calling procedure. Note that in the calling procedure, the variable used to accept the array returned from the function is a simple variant that is never explicitly dimensioned as an array:

    Dim i 
    Dim sReturnedArray 
     
    sReturnedArray = PopulateArray("A")
     
    For i = 0 To UBound(sReturnedArray)
     msgbox sReturnedArray(i)
    Next 
     
    Private Function PopulateArray(sVal)
    
     Dim sTempArray(10) 
     Dim i 
     
     For i = 0 To 10
     sTempArray(i) = sVal & CStr(i)
     Next 
     
     PopulateArray = sTempArray
    
    End Function

Programming Tips and Gotchas

  • There is often confusion between the ByRef and ByVal methods of assigning arguments to the function. ByRef assigns a reference to the variable in the calling procedure to the variable in the function; any changes made to the variable from within the function are in reality made to the variable in the calling procedure. On the other hand, ByVal assigns the value of the variable in the calling procedure to the variable in the function. Changes made to the variable in the function have no effect on the variable in the calling procedure.
  • Functions can return only one value, or can they? Look at the following code:

    Sub testTheReturns( )
    
     Dim iValOne
     
     iValOne = 10
     If testValues(iValOne) Then
     Msgbox iValOne
     End If
     
    End Sub
    
    Function testValues(ByRef iVal)
    
     iVal = iVal + 5
     testValues = True
     
    End Function

    Because the argument was passed ByRef, the function acted upon the underlying variable iValOne. This means you can use ByRef to obtain several "return" values (although they're not strictly return values) from a single function call.

  • There are many occasions where you will run into the dreaded (by some!) recursive function call. Recursion occurs when you call a function from within itself. Recursion is a legitimate and often essential part of software development; for example, it's an efficient method for enumerating or iterating a hierarchical structure. However, you must be aware that recursion can lead to stack overflow. The extent to which you can get away with recursion really depends upon the complexity of the function concerned, the amount and type of data being passed in, and an infinite number of other variables and unknowns.

See Also

Sub Statement

GetLocale Function  

Syntax

GetLocale( )

Return Value

A Long indicating the current locale ID.

Description

Gets the current locale ID.

Rules at a Glance

  • A locale ID represents a language as well as regional conventions. It determines such things as keyboard layout, alphabetic sort order, and date, time, number, and currency formats.
  • Appendix D lists valid locale IDs.

Programming Tips and Gotchas

  • If you want to temporarily change the locale, there is no need to call GetLocale and store its returned value before calling SetLocale, since SetLocale returns the value of the previous locale ID.
  • GetLocale returns the locale ID currently in use by the script engine.
  • Although you can set the locale using either a decimal, hexadecimal, or string locale ID, the GetLocale function returns only a decimal locale ID value.
  • The default value of the script engine's locale ID is determined as follows: When the script engine starts up, the host passes it a locale ID. If the host does not do so, the script engine uses the user's default locale ID. If there is no user, then the script engine uses the system's default locale ID.
  • Note that the script engine's locale ID is different from the system locale ID, the user locale ID, and the host application's locale ID. The GetLocale function reports the locale ID in use by the script engine only.

VBA/VBScript Differences

The GetLocale function is not supported by VBA.

See Also

SetLocale Function

GetObject Function  

Syntax

GetObject([pathname] [, class])

pathname

Use: Optional

Data Type: String

The full path and filename of a file that stores the state of an automation object, or a moniker (that is, a name that represents an object) along with the information required by the syntax of the moniker to identify a specific object.

class

Use: Optional

Data Type: String

The object's programmatic identifier (ProgID), as defined in the system registry.

Return Value

A reference to an ActiveX object.

Description

Returns a reference to an automation object. The GetObject function has three functions:

  • It retrieves references to objects from the Running Object Table.
  • It loads persisted state into objects.
  • It creates objects based on monikers.

Rules at a Glance

  • Although both pathname and class are optional, at least one argument must be supplied.
  • GetObject can be used to retrieve a reference to an existing instance of an automation object from the Running Object Table. For this purpose, you supply the object's programmatic identifier as the class argument. However, if the object cannot be found in The Running Object Table, GetObject is unable to create it and instead returns runtime error 429, "ActiveX component can't create object." To create a new object instance, use the CreateObject function.
  • If you specify a class argument and specify pathname as a zero-length string, GetObject returns a new instance of the objectunless the object is registered as single instance, in which case the current instance is returned. For example, the following code launches Excel and creates a new instance of the Excel Application object:

    Dim excel
    Set excel = GetObject (" ", "Excel. Application")

    In this case, the effect of the function is similar to that of CreateObject.

  • To assign the reference returned by GetObject to your object variable, you must use the Set statement:

    Dim myObject
    Set myObject = GetObject("C:OtherAppLibrary.lib")

    To load an object's persisted state into an object, supply the filename in which the object is stored as the pathname argument and omit the class argument.

  • The details of how you create different objects and classes are determined by how the server has been written; you need to read the documentation for the server to determine what you need to do to reference a particular part of the object. There are three ways you can access an ActiveX object:

    • The overall object library. This is the highest level, and it gives you access to all public sections of the library and all its public classes:

      GetObject("C:OtherAppLibrary.lib")
    • A section of the object library. To access a particular section of the library, use an exclamation mark (!) after the filename, followed by the name of the section:

      GetObject("C:OtherAppLibrary.lib!Section")
    • A class within the object library. To access a class within the library, use the optional Class parameter:

      GetObject("C:OtherAppLibrary.lib", "App.Class")
  • To instantiate an object using a moniker, supply the moniker along with its required arguments. For details, see the discussion of monikers in the Programming Tips and Gotchas section.

Example

The example uses the IIS moniker to retrieve a reference to the IIS metabase. It then iterates the IIS metabase class hierarchy and writes the names of all classes to a file. Its code is:

Dim oIIS, oFS, msg, txtStream, filename

fileName = "C:  IISClasses.txt"

Set oIIS = GetObject ("IIS:// localhost")
IterateClasses oIIS, 0
Set oFS = CreateObject ("Scripting.FileSystemObject")
txtStream.Write msg
txtStream. Close

MsgBox "IIS Metabse information written to " & filename

Sub IterateClasses (collec, indent)

 Dim oItem

 For Each oItem In collec
 msg = msg & space(indent) & oItem.Name & vbCrL
 IterateClasses oItem, indent + 3f
 Next
End Sub

Programming Tips and Gotchas

  • Pay special attention to objects registered as single instance. As their type suggests, there can be only one instance of the object created at any one time. Calling CreateObject against a single-instance object more than once has no effect; you still return a reference to the same object. The same is true of using GetObject with a pathname of " "; rather than returning a reference to a new instance, you obtain a reference to the original instance of the object. In addition, you must use a pathname argument with single-instance objects (even if this is " "); otherwise an error is generated.
  • You can't use GetObject to obtain a reference to a class created with VBScript; this can only be done using the New keyword.
  • The following table shows when to use GetObject and CreateObject :

Use

Task

CreateObject

Create a new instance of an OLE server

CreateObject

Create a subsequent instance of an already instantiated server (if the server isn't registered as single instance)

GetObject

Obtain a further reference to an already instantiated server without launching a subsequent instance

GetObject

Launch an OLE server application and load an instance of a subobject

CreateObject

Instantiate a class registered on a remote machine

GetObject

Instantiate an object using a moniker

  • A moniker is simply a name that represents an object without indicating how the object should be instantiated. (It contrasts with a programmatic identifier, for instance, which indicates that information stored in the system registry is used to locate and instantiate an object.) The following are some of the valid monikers recognized by the GetObject function, along with their required arguments:

Moniker

Arguments

Description

IIS:

metabasepath

Retrieves a reference to an IIS metabase object, which allows the programmer to view or modify the configuration of IIS

JAVA:

classname

Returns a reference to an unregistered Java object stored in the java rustlib folder

SCRIPT:

path

Returns a reference to an unregistered Windows Script Component

CLSID:

clsid

Returns a reference to an object based on its class identifier (ClsID) in the system registry

WINMGMTS:

string

Returns a reference to a WMI object that allows access to core Windows functionality

QUEUE:

clsid or progid

Uses MSMQ to return a reference to a queued COM+ component

NEW:

clsid or progid

Creates a new instance of any COM component that supports the IClassFactory interface (that is, of any createable COM component)

See Also

CreateObject Function, Set Statement

The VBScript GetRef Function

Programming Tips and Gotchas

  • A common use of GetRef is to bind to DHTML events in Internet Explorer. You can use GetRef to bind to any of the events in the DHTML object model.
  • GetRef can be used to pass the address of a procedure to a routine that expects the address of a callback function as an argument.

VBA/VBScript Differences

The GetRef function is not supported by VBA. However, similar functionality is provided in VBA by the AddressOf operator, which returns a pointer to (or the address of) a procedure.

See Also

Function Statement, Sub Statement, Set Statement

GetRef Function  

Syntax

GetRef(procname)

procname

Use: Required

Data Type: String

Name of a sub or function

Return Value

A Long containing a reference to procname.

Description

Returns a reference to a sub or function. This reference can be used for such purposes as binding to events or defining callback functions.

Rules at a Glance

  • GetRef can be used whenever a function or procedure reference is expected.
  • When using GetRef to define event handlers for events, the Set keyword is required. For example, the code required to bind the Window.OnLoad event to a procedure named ShowGreetingDialog is:

    Set Window.OnLoad = GetRef("ShowGreetingDialog")

Example


 
Hex Function  

Syntax

Hex(number)

number

Use: Required

Data Type: Numeric or String

A valid numeric or string expression.

Return Value

String representing the hexadecimal value of number.

Description

Returns a string that represents the hexadecimal value of a number.

Rules at a Glance

  • If number contains a fractional part, it's rounded automatically to the nearest whole number prior to processing. If the number ends in .5, it's rounded to the nearest even whole number.
  • number must evaluate to a numeric expression that ranges from -2,147,483,648 to 2,147,483,647. If the argument is outside this range, runtime error 6, "Overflow," results.
  • The return value of Hex is dependent upon the value and type of number :

number

Return value

Null

Null

Empty

Zero (0)

Any other number

Up to eight hexadecimal characters

Programming Tips and Gotchas

If the value of number is known beforehand and isn't the result of an expression, you can represent the number as a hexadecimal by simply affixing &H to number. Each of the following statements assigns a hexadecimal value to a variable:

lngHexValue1 = &HFF ' Assigns 255

VBA/VBScript Differences

The Hex$ function is not available in VBScript.

See Also

Oct Function

Hour Function  

Syntax

Hour(time)

time

Use: Required

Data Type: Any expression that can be converted to a date.

Any valid time expression.

Return Value

A variant of data type Integer representing the hour of the day.

Description

Extracts the hour element from a time expression.

Rules at a Glance

  • Hour returns a whole number between 0 and 23, representing the hour of a 24-hour clock.
  • If time contains Null, Null is returned.

See Also

Minute Function, Now Function, Second Function

If . . . Then . . . Else Statement  

Syntax

If condition Then
 [statements]
[ElseIf condition-n Then
 [elseifstatements] ...
[Else
 [elsestatements]]
End If

Or, you can use the single-line syntax:

If condition Then [statements] [Else elsestatements]

condition

Use: Required

Data Type: Boolean

An expression returning either True or False or an object type.

statements

Use: Optional

Program code to be executed if condition is True.

condition-n

Use: Optional

Same as condition.

elseifstatements

Use: Optional

Program code to be executed if the corresponding condition-n is True.

elsestatements

Use: Optional

Program code to be executed if the corresponding condition or condition-n is False.

Description

Executes a statement or block of statements based on the Boolean (True or False) value of an expression.

Rules at a Glance

  • If condition is True, the statements following the If statement are executed.
  • If condition is False and no Else or ElseIf statement is present, execution continues with the corresponding End If statement. If condition is False and ElseIf statements are present, the condition of the next ElseIf is tested. If condition is False, and an Else is present, the statements following the Else are executed.
  • In the block form, each If statement must have a corresponding End If statement. ElseIf statements don't have their own End If. For example:

    If condition Then
     statements
    ElseIf condition Then
     statements
    End If
  • ElseIf and Else are optional, and any number of ElseIf and Else statements can appear in the block form. However, no ElseIf statements can appear after an Else.
  • condition can be any statement that evaluates to True or False.
  • If condition returns Null, it's treated as False.
  • statements are optional only in the block form of If. However, statements are required when using the single-line form of If in which there is no Else clause.

Programming Tips and Gotchas

  • You can use the single-line form of the If statement to execute multiple statements, which you can specify by delimiting the statements using colons; however, single-line form If statements are hard to read and maintain, and should be avoided for all but the simplest of situations.
  • In situations where you have many possible values to test, you will find the Select Case statement much more flexible, manageable, and readable than a bunch of nested If statements.
  • You will come across situations in which very large blocks of code have to execute based one or more conditions. In theseand in all situationsyou should try to make your code as readable as possible, not only for other programmers, but for yourself when you try to maintain the code several months down the line. Take a common scenario in which, at the beginning of a procedure, a check is made to see if the procedure should in fact be executed under the current circumstances. You have the choice of surrounding the whole code with an If...Then...End If construct, like this:

    If iSuccess Then
     ...
     ...
     ... 'x000 lines of code
    End If

    Or you can switch the result to look for a False, then exit the sub, like this:

    If Not iSuccess Then
     Exit Sub
    End If
    .... 'x000 lines of code

    The difference is that, with the second method, you don't have to scroll down screens worth of code looking for the matching End If.

  • Indentation is important for the readability of If, and especially nested If, statements. The recommended indentation is four characters. The set of statements within each new If...Else...End If block should be indented. The following example shows correctly indented code:

    If x = y Then
     DoSomethingHere
     If y < z Then
     DoSomethingElseToo
     Else
     DoAnotherThing
     If z = 101 Then
     DoAThing
     End If
     End If
    Else
     DoAlternative
    End If
  • Use of the If statement requires some understanding of the implicit and explicit use of True in VBScript. The following If statement uses an implicit True:

    If iSuccess Then

    Notice that you are allowing VBScript to evaluate the iSuccess variable to True or False. When this implicit form is used, any nonzero value evaluates to True, and conversely, a zero value evaluates to False. The following code evaluates iSuccess as True and prints the "OK" message box:

    Dim iSuccess
    iSuccess = 41 
    If iSuccess Then
     MsgBox "OK"
    Else
     MsgBox "False"
    End If

    However, when you compare a variable to an explicit True or False, the value must be -1 to evaluate to True, and 0 for False. If you amend:

    iSuccess = 41
    If iSuccess = True Then

    iSuccess doesn't evaluate to VB's version of True (-1). As you can imagine, this can lead to some confusion, since a variable can evaluate to True when using an implicit comparison but not when using an explicit comparison. Actually, just to add to the confusion, you could get the explicit comparison to behave the same as the implicit one by converting iSuccess to a Boolean:

    If CBool(iSuccess) = True Then

    This isn't entirely recommended, but it does show that VBScript's built-in constants of True and False evaluate only -1 and 0, respectively.

  • Logical comparison operators can be included in the condition expression, allowing you to make decisions based on the outcome of more than one individual element. The most common are And and Or. You can create:

    If x = 1 And y = 3 Then
  • VBScript always evaluates both sides of a logical comparison, unlike some languages that stop once the value of the expression is known; this is known as short circuiting. For example, in the following code, if x does equal 1, then the If condition is true. Some languages would stop the evaluation here. But regardless of the value of x, VBScript still evaluates the comparison with y . This means that the second part of an expression can generate an error even if the result of the expression is already known. This is the case if the second comparison assumes the truth or falsity of the first comparison. For example:

    If (Not x Is Nothing) And x.SomeProperty = 123 Then 'BAD CODE

    Here, the first comparison tests whether x is a valid object reference. But the second comparison, which tests the value of the value of x's SomeProperty property, presupposes that x is a valid object reference.

    If x = 1 Or y = 3 Then
  • The If statement is also used with objects to determine if an object reference has been successfully assigned to an object variable. (Actually, that's not completely accurate; you check to see whether the object variable is still set to Nothing.) However, you can't use the equality operator (=) for this comparison. Instead, you must use the object comparison operator Is:

    If Not objectname Is Nothing Then

VBA/VBScript Differences

In VBA, you can determine an object type with a statement like:

If TypeOf oObj Is CClass Then

In VBScript, however, the TypeOf operator is not supported; you must use the TypeName function instead.

See Also

Select Case Statement

Initialize Event  

Syntax

Sub object_Initialize( )

Description

Use the Initialize event of a class defined with the Class...End Class construct to prepare the object or class for use, setting any references to subobjects or assigning default values to properties and values to class-level variables.

Rules at a Glance

  • The Initialize event is triggered automatically when a class is first instantiated by the Set statement. For example, in the following code, the Set statement generates the Initialize event:

    Dim MyObject As MyClass
    'some code
    ...
    'initialize event called here
    Set MyObject = New MyClass
    StrName = MyObject.CustName
  • The Initialize event doesn't take any arguments.
  • It is best to declare the Initialize event as Private, although this is not required.

Programming Tips and Gotchas

  • While it's possible to explicitly call the Initialize event from within the object at any stage after the object has been created, it isn't recommended, because the code in the Initialize event should be written to be "run once" code.
  • Use the Initialize event of a class module to generate references to dependent objects. For example:

    Option Explicit
    
    Dim custOrder
    Set custOrder = New Order
    ' ...other code
    
    Class Order
     Private cust, itemsOrdered
     Private Sub Class_Initialize()
     Set cust = New Customer
     Set itemsOrdered = New Items
     End Sub
    End Class
    
    Class Customer
     ' Implementation of Customer
    End Class
    
    Class Items
     Dim orderItem(10)
    
     Private Sub Class_Initialize()
     Set orderItem(0) = New Item
     End Sub
     ' Other implementation details of Items collection
    End Class
    
    Class Item
     ' Implementation of Item
    End Class
  • The Initialize event is triggered only once, when a new object is created. When an object variable is assigned a reference to an existing object, the Initialize event isn't invoked. For example, in the following code fragment, the Initialize event is invoked only once when the Set objMine1 statement is executed:

    Dim objMine1, objMine2
    Set objMine1 = New MyObj
    Set objMine2 = objMine1

See Also

Set Statement, Terminate Event

InputBox Function  

Syntax

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

prompt

Use: Required

Data Type: String

The message in the dialog box.

title

Use: Optional

Data Type: String

The titlebar of the dialog box.

default

Use: Optional

Data Type: String

String to be displayed in the text box on loading.

xpos

Use: Optional

Data Type: Numeric

The distance from the left side of the screen to the left side of the dialog box.

ypos

Use: Optional

Data Type: Numeric

The distance from the top of the screen to the top of the dialog box.

helpfile

Use: Optional

Data Type: String

The Help file to use if the user clicks the Help button on the dialog box.

context

Use: Optional

Data Type: Numeric

The context number to use within the Help file specified in helpfile.

Return Value

InputBox returns a variant string containing the contents of the text box from the InputBox dialog.

Description

Displays a dialog box containing a label, which prompts the user about the data you expect them to input, a text box for entering the data, an OK button, a Cancel button, and optionally, a Help button. When the user clicks OK, the function returns the contents of the text box.

Rules at a Glance

  • If the user clicks Cancel, a zero-length string (" ") is returned.
  • prompt can contain approximately 1,000 characters, including nonprinting characters like the intrinsic vbCrLf constant.
  • If the title parameter is omitted, "VBScript" is displayed in the titlebar.
  • If you don't use the default parameter to specify a default entry for the text box, the text box is shown empty; a zero-length string is returned if the user doesn't enter anything in the text box prior to clicking OK.
  • xpos and ypos are specified in twips. A twip is a device-independent unit of measurement that equals 1/20 of a point or 1/1440 of an inch.
  • If the xpos parameter is omitted, the dialog box is centered horizontally.
  • If the ypos parameter is omitted, the top of the dialog box is positioned approximately one-third of the way down the screen.
  • If the helpfile parameter is provided, the context parameter must also be provided, and vice versa.
  • In VBScript, when both helpfile and context are passed to the InputBox function, a Help button is automatically placed on the InputBox dialog, allowing the user to click and obtain context-sensitive help.

Programming Tips and Gotchas

  • If you are omitting one or more optional arguments and using subsequent arguments, you must use a comma to signify the missing argument. For example, the following code fragment displays a prompt, a default string in the text box, and the help button, but default values are used for the title and positioning.

    sString = InputBox("Enter it now", , "Something", , _
     , "help.hlp", 321321)
  • Because it is a user-interface element that would execute on the server, the InputBox function should not be used in Active Server Pages or it will generate runtime error 70, "Permission denied."
  • In a client-side web page, it's preferable to rely on HTML intrinsic controls with validation using client-side script, rather than on the InputBox function.

VBA/VBScript Differences

In VBA, in an Office-hosted environment, the maximum length of prompt is 256 characters. This limitation doesn't exist in VBScript.

See Also

MsgBox Function

InStr, InStrB Functions  

Syntax

InStr([start, ]stringtosearch, stringtofind[, comparemode])

start

Use: Optional

Data Type: Numeric

The starting position for the search.

stringtosearch

Use: Required

Data Type: String

The string being searched.

stringtofind

Use: Required

Data Type: String

The string being sought.

comparemode

Use: Optional

Data Type: Integer

The type of string comparison.

Return Value

A Long.

Description

Finds the starting position of one string within another.

Rules at a Glance

  • The return value of InStr is influenced by the values of stringtosearch and stringtofind, as shown in the following table:

Condition

InStr return value

stringtosearch is zero-length

0

stringtosearch is Null

Null

stringtofind is zero-length

start

stringtofind is Null

Null

stringtofind is not found

0

stringtofind is found within stringtosearch

Position at which the start of stringtofind is found

start > len(stringtofind)

0

  • If the start argument is omitted, InStr commences the search with the first character of stringtosearch.
  • If the start argument is Null, an error occurs.
  • You must specify a start argument if you are specifying a comparemode argument.
  • VBScript supports intrinsic constants for comparemode, as follows:

    Comparison mode

    Value

    Constant

    Binary (default)

    0

    vbBinaryCompare

    Textcase- insensitive

    1

    vbTextCompare

    In effect, a binary comparison means that the search for stringtofind in stringtosearch is case-sensitive. A text comparison means that the search for stringtofind in stringtosearch is not case-sensitive.

  • If the comparemode argument contains Null, an error is generated.
  • If comparemode is omitted, the type of comparison is vbBinaryCompare.

Programming Tips and Gotchas

You can use the InStrB function to compare byte data contained within a string. In this case, InStrB returns the byte position of stringtofind, as opposed to the character position.

VBA/VBScript Differences

In VBA, the default value of the compare parameter is determined by the setting of the Option Compare statement. VBScript, however, does not support the Option Compare statement, and comparemode defaults to vbBinaryCompare.

See Also

InstrRev Function, Left, LeftB Functions, Mid, MidB Functions, Right, RightB Functions, StrComp Function

InstrRev Function  

Syntax

InstrRev(sourcestring, soughtstring[, start[, compare]])

sourcestring

Use: Required

Data Type: String

The string to be searched.

soughtstring

Use: Required

Data Type: String

The substring to be found within sourcestring.

start

Use: Optional

Data Type: Numeric

Starting position of the search. If no value is specified, start defaults to 1.

compare

Use: Optional

Data Type: Integer

The method that compares soughtstring with sourcestring ; its value can be vbBinaryCompare or vbTextCompare

Return Value

Variant of type Long.

Description

Determines the starting position of a substring within a string by searching from the end of the string to its beginning.

Rules at a Glance

  • While InStr searches a string from left to right, InStrRev searches a string from right to left.
  • vbBinaryCompare is case-sensitive; that is, InstrRev matches both character and case, whereas vbTextCompare is case-insensitive, matching only character, regardless of case.
  • The default value for compare is vbBinaryCompare.
  • start designates the starting point of the search and is the number of characters from the start of the string.
  • If start is omitted, the search begins from the last character in sourcestring.
  • sourcestring is the complete string in which you want to find the starting position of a substring.
  • If soughtstring isn't found, InStrRev returns 0.
  • If soughtstring is found within sourcestring, the value returned by InStrRev is the position of sourcestring from the start of the string.

Programming Tips and Gotchas

One of the useful applications of InstrRev is to search backward through a path and filename to extract each successive component.

Example

This example uses both InStr and InStrRev to highlight the different results produced by each. Using a sourcestring that states "I like the functionality that InStrRev gives," InStr finds the first occurrence of "th" at character 8, while InStrRev finds the first occurrence of "th" at character 26:

Dim myString
Dim sSearch
myString = "I like the functionality that InStrRev gives"
sSearch = "th"

Msgbox InStr(myString, sSearch)						 
Msgbox InStrRev(myString, sSearch) 

See Also

InStr, InStrB Functions

Int Function  

Syntax

Int(number)

number

Use: Required

Data Type: Any valid numeric data type

The number to be truncated.

Return Value

Returns a value of the numeric data type passed to it.

Description

Returns the integer portion of a number.

Rules at a Glance

  • The fractional part of number is removed and the resulting integer value returned. Int doesn't round number to the nearest whole number; for example, Int(100.9) returns 100.
  • If number is negative, Int returns the first negative integer less than or equal to number ; for example, Int(-10.1) returns -11.

Programming Tips and Gotchas

  • Int and Fix work identically with positive numbers. However, for negative numbers, Fix returns the first negative integer greater than number. For example, Int(-10.1) returns -10.
  • Don't confuse the Int function with CInt. CInt casts the number passed to it as an Integer data type, whereas Int returns the same data type that was passed to it.

See Also

Fix Function

Is Operator  

Syntax

object1 Is object2

object1

Use: Required

Data Type: Object

An object variable.

object2

Use: Required

Data Type: Object

A second object variable.

Return Value

Boolean.

Description

Compares two object variables to determine whether they reference the same object.

Rules at a Glance

  • Both object1 and object2 must be object references, or runtime error 424, "Object required," results.
  • The operation returns a result of True if the object references are identical and False if they are not.
  • It is also possible to determine whether an object contains a valid reference by replacing object2 with the special Nothing keyword. For example:

    If oDrive Is Nothing Then

    returns True if oDrive does not refer to an object and False if it does. This should be used to test for an uninitialized object reference.

Programming Tips and Gotchas

  • Note that objects in VBScript are referencesthat is, they reference an object in memory. This means that if two variables reference the same object and you make changes to the object's properties using the first object variable, those changes are reflected when you retrieve the object's property settings using the second object variable.
  • You may wonder why there is a special Is operator for objects. When you perform a comparison of scalar variables, you want to know whether their values are the same. But in the case of objects, you want to know whether two references point to a single object. (Many objects have identical property values; a test for equal values is meaningless.) This is the reason for the Is operator.
  • You can create identical object references in a number of ways. One is by assigning an existing reference to a second object variable:

    Dim oDrive1, oDrive2
    Set oDrive1 = oFS.Drives("C")
    Set oDrive2 - oDrive1

    You can also set two objects equal to a third object reference:

    Dim oDrive1, oDrive2, oDrive
    Set oDrive = oFS.Drives("C")
    Set oDrive1 = oDrive
    Set oDrive2 = oDrive

    Finally, you can set both object references equal by retrieving them from the same object in an object model. For example:

    Dim oDrive1, oDrive2
    Set oDrive1 = oFS.Drives("C")
    Set oDrive2 - oFS.Drives("C")
  • Typically, the Is operator is used in an If...Then...Else construct to take some action if objects are the same or if an object reference does not point to a valid object.
IsArray Function  

Syntax

IsArray(varname)

varname

Use: Required

Data Type: Any

The name of the variable to be checked.

Return Value

Boolean (True or False).

Description

Tests whether a variable is an array.

Rules at a Glance

If the variable passed to IsArray is an array or contains an array, True is returned; otherwise, IsArray returns False.

Programming Tips and Gotchas

Due to the nature of variants, it isn't always obvious if a variant variable contains an array, especially if you pass the variant to a function, and the function may or may not attach an array to the variant. Calling any of the array functions such as LBound or UBoundor trying to access an element in an array that doesn't exist will obviously generate an error. In these situations, you should first use the IsArray function to determine whether you can safely process the array.

IsDate Function  

Syntax

IsDate(expression)

expression

Use: Required

Data Type: Any.

Variable or expression containing a date or time.

Return Value

Boolean (True or False).

Description

Determines whether a variable's value can be converted to a date.

Rules at a Glance

If the expression passed to IsDate is a valid date, True is returned; otherwise, IsDate returns False.

Programming Tips and Gotchas

  • IsDate uses the locale settings of the current Windows system to determine whether the value held within the variable is recognizable as a date. Therefore, what is a legal date format on one machine may fail on another.
  • IsDate is particularly useful for validating data input.
IsEmpty Function  

Syntax

IsEmpty(varname)

varname

Use: Required

Data Type: Any

A numeric or string expression.

Return Value

Boolean (True or False).

Description

Determines whether the variable has been initialized by having an initial value (other than Empty) assigned to it.

Rules at a Glance

  • If the variant passed to IsEmpty has not been initialized, True is returned; otherwise, IsEmpty returns False.
  • Although IsEmpty can take an expression as the value of varname, it always returns False if more than one variable is used in the expression. IsEmpty is therefore most commonly used with single variables.

Programming Tips and Gotchas

When passed an object variable that has been set equal to Nothing, the IsEmpty function returns False. Hence, the function should not be used to test whether a previously initialized object variable now holds a valid object reference.

IsNull Function  

Syntax

IsNull(expression)

expression

Use: Required

Data Type: Any

An expression containing string or numeric data.

Return Value

Boolean (True or False).

Description

Determines whether expression contains is Null.

Rules at a Glance

  • If the expression passed to IsNull is Null, True is returned; otherwise, IsNull returns False.
  • All variables in expression are checked for null values. If a null value is found in any one part of the expression, True is returned for the entire expression.
  • In VBScript, Null is a separate data type that can take on a single value, Null. It is used to indicate that data is missing. Because it represents missing data, all expressions that include a Null value also result in a Null value. This makes perfect sense. For instance, if we have an array containing two valid months of sales data and a Null representing the third month's sales data, the quarter's sales data should also be Null, since accurate data for the quarter is not available.

Programming Tips and Gotchas

  • IsNull is useful when returning data from a database. You should check field values in columns that allow Nulls against IsNull before assigning the value to a collection or other variable. This stops the common "Invalid Use of Null" error from occurring.
  • IsNull is the only way to evaluate an expression containing a null. For example, the seemingly correct statement:

    If varMyVar = Null Then

    always evaluates to False, even if varMyVar is null. This occurs because the value of an expression containing Null is always Null, and therefore False.

IsNumeric Function  

Syntax

IsNumeric(expression)

expression

Use: Required

Data Type: Any

A numeric or string expression.

Return Value

Boolean (True or False).

Description

Determines whether expression can be evaluated as a number.

Rules at a Glance

If the expression passed to IsNumeric evaluates to a number, True is returned; otherwise, IsNumeric returns False.

Programming Tips and Gotchas

  • If expression is a date or time, IsNumeric evaluates to False.
  • If expression is a currency value, including a string that includes the currency symbol defined by the Control Panel's Regional Settings applet, IsNumeric evaluates to True.
IsObject Function  

Syntax

IsObject(varname)

varname

Use: Required

Data Type: Any

Name of the variable to be evaluated.

Return Value

Boolean (True or False).

Description

Indicates whether a variable contains a reference to an objectin other words, if it's an object variable.

Rules at a Glance

If the variable passed to IsObject references or has referenced an object, even if its value is Nothing, True is returned; otherwise, IsObject returns False.

Programming Tips and Gotchas

  • IsObject doesn't validate the reference being held by an object variable; it simply determines whether the variable is an object. To ensure that an object reference is valid, you can use the syntax Is Nothing, as shown in this code snippet:

    If objVar Is Nothing Then
    ...
    End if
  • IsObject is simply a "convenience" function that is roughly equivalent to the following user-defined function:

    Public Function IsObject(varObj)
    
    If VarType(varObj) = vbObject Then
     IsObject = True
    Else
     IsObject = False
    End If
    
    End Function
Join Function  

Syntax

result = Join(sourcearray, [delimiter])

sourcearray

Use: Required

Data Type: Array

Array whose elements are to be concatenated.

delimiter

Use: Optional

Data Type: String

Character used to delimit the individual values in the string.

Return Value

A type String.

Description

Concatenates an array of values into a delimited string using a specified delimiter.

Rules at a Glance

  • If no delimiter is specified, the space character is used as a delimiter.
  • The members of sourcearray must be convertible to strings. The individual members of sourcearray can be any data type except Object. In fact, the individual members of sourcearray can be objects as long as the object's default member is not another object. For example, the Join function in the code fragment:

    Set oFS = CreateObject("Scripting.FIleSystemObject")
    Set oDrive1 = oFS.Drives("C")
    Set oDrive2 = oFS.DRives("D")
    
    Set vArr(0) = oDrive1
    Set vArr(1) = oDrive2
    
    sJoin = Join(vArr, ",")
    returns the string "C:,D:".
  • When a delimiter is specified, unused sourcearray elements are noted in the return string by the use of the delimiter. For example, if you specify a delimiter of "," and a source array with 11 elements, of which only the first two are used, Join returns a string similar to the following:

    "a,b,,,,,,,,,"

Programming Tips and Gotchas

The Join function is ideal for quickly and efficiently writing out a comma-delimited text file from an array of values.

LBound Function  

Syntax

LBound(arrayname[, dimension])

arrayname

Use: Required

Data Type: Array

The name of the array.

dimension

Use: Optional

Data Type: Long

A number specifying the dimension of the array.

Return Value

A Long.

Description

Determines the lower limit of a specified dimension of an array. The lower boundary is the smallest subscript you can access within the specified array.

Rules at a Glance

If dimension isn't specified, 1 is assumed. To determine the lower limit of the first dimension of an array, set dimension to 1, to 2 for the second, and so on.

Programming Tips and Gotchas

  • This function appears to have little use in VBScript, since VBScript does not allow you to control the lower bound of an array. Its value, which is 0, is invariable. However, it is possible for ActiveX components created using Visual Basic to return a array with a lower bound other than 0 to a VBScript script.
  • LBound is useful when handling arrays passed by ActiveX controls written in VB, since these may have a lower bound other than 0.

VBScript/VB & VBA Differences

Unlike VBA, there is no Option Base available in VBScript, nor does VBScript support the To keyword in the Dim, Private, Public, and ReDim statements. Therefore, all arrays will have a lower bound of 0.

See Also

Array Function, UBound Function

LCase Function  

Syntax

LCase(string)

string

Use: Required

Data Type: String

A valid string expression.

Return Value

A String.

Description

Converts a string to lowercase.

Rules at a Glance

  • LCase affects only uppercase letters; all other characters in string are unaffected.
  • LCase returns Null if string contains a Null.

VBScript/VB & VBA Differences

There is no LCase$ function available in VBScript.

See Also

UCase Function

Left, LeftB Functions  

Syntax

Left(string, length)

string

Use: Required

Data Type: String

The string to be processed.

length

Use: Required

Data Type: Long

The number of characters to return from the left of the string.

Return Value

Left and LeftB return a String.

Description

Returns a string containing the left-most length characters of string.

Rules at a Glance

  • If length is 0, a zero-length string (" ") is returned.
  • If length is greater than the length of string, string is returned.
  • If length is less than 0 or Null, the function generates runtime error 5, "Invalid procedure call or argument," and runtime error 94, "Invalid use of Null," respectively.
  • If string contains Null, Left returns Null.
  • Left processes strings of characters; LeftB is used to process binary data.

Programming Tips and Gotchas

  • Use the Len function to determine the overall length of string.
  • When you use the LeftB function with byte data, length specifies the number of bytes to return.

VBScript/VB & VBA Differences

There are no Left$ or LeftB$ functions available in VBScript.

See Also

Len, LenB Functions, Mid, MidB Functions, Right, RightB Functions

Len, LenB Functions  

Syntax

Len(string | varname)
LenB(string | varname)

string

Use: Required

Data Type: String

A valid string literal or string expression.

varname

Use: Required

Data Type: Any except Object

A valid variable name.

Return Value

Long.

Description

Len returns the number of characters in a string or variable. LenB returns the number of bytes required to store a string in memory.

Rules at a Glance

  • string and varname are mutually exclusive; that is, you must specify either string or varname, but not both.
  • If either string or varname is Null, Len and LenB return Null.
  • You can't use Len or LenB with an object variable.
  • If varname is an array, you must also specify a valid subscript. In other words, Len and LenB can't determine the total number of elements in or the total size of an array. To determine the size of an array, use the LBound and UBound functions.

Programming Tips and Gotchas

  • Nonstring data is treated the same as strings when passed to the Len and LenB functions. For example, in the code:

    Dim number
    number = 100
    WScript.Echo Len(number)

    the Len function returns 3, since that is the number of characters in the value of number.

  • LenB is intended to work with string data, and returns the number of bytes required to store that string. If a nonstring data type is passed to the LenB function, its value is first converted to a string before its length is determined.

VBA/VBScript Differences

Although the Len and LenB functions handle strings identically in VBA and VBScript, they handle non-string data types quite differently. Len and LenB in VBA reports the number of bytes required to store the non-string data type in memory. In contrast, in VBScript, Len reports the number of characters in the string representation of non-character data, and LenB reports the number of bytes needed to store the string representation of noncharacter data.

LoadPicture Function  

Syntax

LoadPicture(picturename)

picturename

Use: Required

Data Type: String

The path and filename of the picture file.

Return Value

A StdPicture object.

Description

Loads a picture object.

Rules at a Glance

  • picturename consists of an optional path along with the name of a supported image file. If the path component of picturename is omitted, the VBScript runtime engine attempts to find the image in the script's current directory.
  • picturename can be a bitmap (.bmp), enhanced metafile (.emf ), icon (.ico), Graphics Interchange Format (.gif ), JPEG (.jpg), run-length encoded (.rle), or Windows metafile (.wmf ).

Example

The following example loads an image into an Outlook contact form:

Function Item_Open( )

Dim oPic

Set oPic = LoadPicture("C:windows" & Item.FullName & ".bmp")

Set Item.GetInspector.ModifiedFormPages("General").imgContact.Picture = _
 oPic
End Function

Programming Tips and Gotchas

  • The StdPicture object is defined by the OLE Automation library STDOLE2.TLB. It supports the members shown in the following table:

Name

Type

Description

Handle

Property

Returns a handle to the image.

Height

Property

Indicates the height of the image in HiMetric units.

hPal

Property

Returns a handle to the Picture object's palette.

Render

Method

Draws all or part of the image to a destination object.

Type

Property

Returns the Picture object's graphics format. Possible values are 0 (none), 1 (bitmap), 2 (metafile), 3 (icon), and 4 (enhanced metafile).

Width

Property

Indicates the width of the image in HiMetric units.

Log Function  

Syntax

Log(number)

number

Use: Required

Data Type: Double

A numeric expression greater than zero.

Return Value

A Double.

Description

Returns the natural logarithm of a given number.

Rules at a Glance

  • The natural logarithm is based on e, a constant whose value is approximately 2.718282. The natural logarithm is expressed by the equation:

    ez = x

    where z = Log(x). In other words, the natural logarithm is the inverse of the exponential function.

  • number, the value whose natural logarithm the function is to return, must be a positive real number. If number is negative or zero, the function generates runtime error 5, "Invalid procedure call or argument."

Programming Tips and Gotchas

  • You can calculate base-n logarithms for any number x, by dividing the natural logarithm of x by the natural logarithm of n, as the following expression illustrates:

    Logn(x) = Log(x) / Log(n)

    For example, the Log10 function shows the source code for a custom function that calculates base-10 logarithms:

    Function Log10(X)
     Log10 = Log(X) / Log(10)
    End Function
  • A number of other mathematical functions that aren't intrinsic to VBScript can be computed using the value returned by the Log function. The functions and their formulas are:

    Inverse Hyperbolic Sine

    HArcsin(X) = Log(X + Sqr(X * X + 1))

    Inverse Hyperbolic Cosine

    HArccos(X) = Log(X + Sqr(X * X - 1))

    Inverse Hyperbolic Tangent

    HArctan(X) = Log((1 + X) / (1 - X)) / 2

    Inverse Hyperbolic Secant

    HArcsec(X) = Log((Sqr(-X * X + 1) + 1) / X)

    Inverse Hyperbolic Cosecant

    HArccosec(X) = Log((Sgn(X) * Sqr(X * X + 1) +1) / X)

    Inverse Hyperbolic Cotangent

    HArccotan(X) = Log((X + 1) / (X - 1)) / 2

LTrim Function  

Syntax

LTrim(stringexp)

stringexp

Use: Required

Data Type: String

A string expression.

Return Value

A String.

Description

Removes any leading spaces from stringexp.

Rules at a Glance

  • LTrim returns a String.
  • If stringexp contains a Null, LTrim returns Null.

Programming Tips and Gotchas

  • Unless you need to keep trailing spaces, it's best to use the Trim function, which is the equivalent of LTrim(RTrim(string)). This allows you to remove both leading and trailing spaces in a single function call.
  • Although we have seen it done, it's extremely unwise to create data relationships that rely on leading spaces. Most string-based data types in relational database management systems like SQL Server and Access automatically remove leading spaces.

VB/VBA Differences

VBScript does not support the VBA LTrim$ function.

See Also

RTrim Function, Trim Function

Match Object  

Description

A member of the Matches collection that is returned by a call to the RegExp object's Execute method, the Match object represents a successful regular expression match.

Createable

No.

Returned by

Matches.Item property.

Properties

The Match object supports the following three properties:

FirstIndex

Data Type: Long

Indicates the position in the original search string where the regular expression match occurred. The first character in the search string is at position 1.

Length

Data Type: Long

Indicates the number of characters in the match found in the search string. This is also the number of characters in the Match object's Value property.

Value

Data Type: String

The text of the match found in the search string.

Example

Since the RegExp object's Execute method searches only a string, the example program writes the filename of each file in the Windows directory to a variable named strNames. Each filename is preceded by two spaces. The RegExp object's Execute method is then called to search for every filename beginning with the letter "B" (the regular expression searches for two spaces followed by a "B"). The Matches collection is then iterated so that each filename can be extracted from strNames and displayed in a message box:

Dim fs, root, dir, fls, fl
Dim rexp
Dim mtchs, mtch
Dim strNames, strMsg
Dim lStartPos

strNames = " "
Set fs = CreateObject("Scripting.FileSystemObject") 
Set root = fs.Drives("C").RootFolder
Set dir = root.SubFolders("Windows")
Set fls = dir.Files

For Each fl In fls
 strNames = strNames & fl.Name & " "
Next
MsgBox Len(strNames)
Set rexp = New RegExp
rexp.Global = True
rexp.Pattern = "(ssB)"
Set mtchs = rexp.Execute(strNames)

For Each mtch In mtchs
 lStartPos = mtch.FirstIndex + 2
 strMsg = strMsg & Mid(strNames, lStartPos, _
 InStr(lStartPos, strNames, " ") - lStartPos + 1) & vbCrLf
Next

MsgBox strMsg

See Also

RegExp Object

Matches Collection Object  

Description

The collection of zero or more Match objects returned by the RegExp object's Execute method; each Match object allows you to identify and manipulate one of the strings found by the regular expression.

Createable

No.

Returned by

RegExp.Execute Method.

Properties

The Matches collection object supports the following two properties:

Count

Data Type: Long

Indicates the number of objects in the collection. A value of zero indicates that the collection is empty. The property is read-only.

Item

Syntax: Matches.Item(index)

Data Type: Match object

Returns a particular Match object based on index, its ordinal position in the collection. Matches is a zero-based collection; that is, its first member is at ordinal position 0, while its last member is at ordinal position Matches.Count - 1.

Example

See the example for the Match object.

See Also

Match Object, RegExp Object, RegExp.Execute Method

Me Keyword  

Syntax

Me

Description

The Me Keyword represents the current instance of the class in which code is executing.

Rules at a Glance

  • Me is an implicit reference to the current object as defined by the Class...End Class statement.
  • Me is automatically available to every procedure in a VBScript class.

Example

In this example, a class method in a WSH script passes an instance of itself to a function outside of the class by using the Me Keyword:

Dim oCtr
Set oCtr = New CCounter
oCtr.Increment
oCtr.Increment
MsgBox "Count: " & oCtr.ShowCount


' definition of CCounter class
Class CCounter

Private lCtr 

Property Get Value
 Value = lCtr
End Property

Private Sub Class_Initialize( )
 lCtr = 1
End Sub

Public Sub Increment( )
 lCtr = lCtr + 1
End Sub

Public Function ShowCount( )
 ShowCount = ShowObjectValue(Me)
End Function

End Class

' Show value of an object's Value property
Public Function ShowObjectValue(oObj)
 ShowObjectValue = oObj.Value
End Function

Programming Tips and Gotchas

  • Values can't be assigned to the Me Keyword.
  • The Me Keyword is particularly useful when passing an instance of the current class as a parameter to a routine outside of the class.

See Also

Class Statement

Mid, MidB Functions  

Syntax

Mid(string, start[, length])

string

Use: Required

Data Type: String

The expression from which to return a substring.

start

Use: Required

Data Type: Long

The starting position of the substring.

length

Use: Optional

Data Type: Long

The length of the substring.

Return Value

A String.

Description

Returns a substring of a specified length from within a given string.

Rules at a Glance

  • If string contains a Null, Mid returns Null.
  • If start is more than the length of string, a zero-length string is returned.
  • If start is less than zero, error 5, "Invalid procedure call or argument," is generated.
  • If length is omitted or is greater than the length of string, all characters from start to the end of string are returned.
  • The MidB version of the Mid function is used with byte data held within a string. When using MidB, both start and length refer to numbers of bytes as opposed to numbers of characters.

Example

The following example is a function that parses a string passed to it as a parameter and writes each word to a dynamic array. Note the use of the InStr function to determine the position of a space, which in this case is the character that can terminate a word:

Public Function ParseString(strString)

Dim arr( )
Dim intStart, intEnd, intStrLen, intCtr

intCtr = 0
intStart = 1
intStrLen = Len(strString)
Redim Preserve arr(10)

Do While intStart > 0
 intEnd = InStr(intStart, strString, " ") - 1
 If intEnd <= 0 Then intEnd = intStrLen
 If intCtr > UBound(arr) Then
 Redim Preserve arr(UBound(arr)+10)
 End If 
 arr(intCtr) = Mid(strString, intStart, _
 intEnd - intStart + 1)
 intStart = intEnd + 2
 intCtr = intCtr + 1
 If intStart > intStrLen Then intStart = 0
Loop

ParseString = arr

End Function

Programming Tips and Gotchas

  • Use the Len function to determine the total length of string.
  • Use InStr to determine the starting point of a given substring within another string.

VBA/VBScript Differences

  • Because it does not support strong typing, VBScript does not support the Mid$ and MidB$ functions, which explicitly return a string, rather than a String.
  • VBA supports the Mid statement, which allows a portion of the string to be replaced with another substring. For example:

    Dim strPhrase As String
    
    strPhrase = "This will be the day."
    Mid(strPhrase, 3, 2) = "at"

    changes the value of strPhrase to "That will be day." This usage of Mid in statement form is not supported by VBScript.

See Also

Left, LeftB Functions; Len, LenB Functions; Right, RightB Functions

Minute Function  

Syntax

Minute(time)

time

Use: Required

Data Type: Date

Any valid date/time expression, or an expression that can be evaluated as a date/time expression.

Return Value

An Integer.

Description

Returns an integer between 0 and 59 representing the minute of the hour from a given date/time expression.

Rules at a Glance

If time is Null, the Minute function returns Null.

Programming Tips and Gotchas

If time isn't a valid date/time expression, the function generates runtime error 13, "Type mismatch." To prevent this, use the IsDate function to check the argument before calling the Minute function.

See Also

Hour Function, Second Function

Month Function  

Syntax

Month(date)

date

Use: Required

Data Type: Date

Any valid date expression.

Return Value

An Integer between 1 and 12.

Description

Returns a variant representing the month of the year of a given date expression.

Rules at a Glance

If date contains Null, Month returns Null.

Programming Tips and Gotchas

  • The validity of the date expression and the position of the month element within the date expression are initially determined by the locale settings of the current Windows system. However, some intelligence has been built into the Month function that surpasses the usual comparison of a date expression to the current locale settings. For example, on a Windows machine set to U.S. date format (mm/dd/yyyy), the date "13/12/2000" is technically illegal. However, the Month function returns 12 when passed this date. The basic rule for the Month function is that if the system-defined month element is outside legal bounds (i.e., greater than 12), the system-defined day element is assumed to be the month and is returned by the function.
  • Since the IsDate function adheres to the same rules and assumptions as Month, it determines whether a date is valid before passing it to the Month function.

See Also

DatePart Function, Day Function, IsDate Function, MonthName Function, Year Function

MonthName Function  

Syntax

MonthName monthnumber [, abbreviate]

monthnumber

Use: Required

Data Type: Long

The ordinal number of the month, from 1 to 12.

abbreviate

Use: Optional

Data Type: Boolean

A flag to indicate whether an abbreviated month name should be returned.

Return Value

A String.

Description

Returns the month name of a given month. For example, 1 returns January, or if abbreviate is True, Jan.

Rules at a Glance

The default value for abbreviate is False.

Programming Tips and Gotchas

monthnumber must be an integer or a long; it can't be a date. Use DatePart("m", dateval) to obtain a month number from a date.

See Also

DatePart Function, Month Function, WeekdayName Function

MsgBox Function  

Syntax

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

prompt

Use: Required

Data Type: String

The text of the message to display in the message box dialog.

buttons

Use: Optional

Data Type: Numeric

The sum of the Button, Icon, Default Button, and Modality constant values.

title

Use: Optional

Data Type: String

The title displayed in the titlebar of the message box dialog.

helpfile

Use: Optional

Data Type: String

An expression specifying the name of the help file to provide help functionality for the dialog.

context

Use: Optional

Data Type: Numeric

An expression specifying a context ID within helpfile.

Return Value

An Integer indicating the button clicked by the user.

Description

Displays a dialog box containing a message, buttons, and optional icon to the user. The action taken by the user is returned by the function as an integer value.

Rules at a Glance

  • prompt can contain approximately 1,000 characters, including carriage return characters such as the built-in vbCrLf constant.
  • In order to divide prompt onto multiple lines, you can use any of the vbCr, vbLf, vbCrLf, or vbNewLine constants. For example:

    SMsg = "This is line 1" & vbCrLf & _
    "This is line 2"
  • If the title parameter is omitted, the text of title depends on the type of script being executed, as the following table shows:

Script type

Caption

ASP script

not applicable

IE script

"VBScript"

Outlook form

"VBScript"

WSH script

"VBScript"

  • If the helpfile parameter is provided, the context parameter must also be provided, and vice versa.
  • When both helpfile and context are passed to the MsgBox function, a Help button is automatically placed on the MsgBox dialog, allowing the user to click and obtain context-sensitive help.
  • If you omit the buttons argument, the default value is 0; VB opens an application modal dialog containing only an OK button.
  • The following intrinsic constants can be added together (or logically Or'ed) to form a complete buttons argument:

    ButtonDisplayConstant + IconDisplayConstant + _
    DefaultButtonConstant + ModalityConstant

    Only one constant from each group can make up the overall buttons value.

Button Display Constants

Constant

Value

Buttons to display

vbOKOnly

0

OK only

vbOKCancel

1

OK and Cancel

vbAbortRetryIgnore

2

Abort, Retry, and Ignore

vbYesNoCancel

3

Yes, No, and Cancel

vbYesNo

4

Yes and No

vbRetryCancel

5

Retry and Cancel

Icon Display Constants

Constant

Value

Icon To display

vbCritical

16

Critical Message

vbQuestion

32

Warning Query

vbExclamation

48

Warning Message

vbInformation

64

Information Message

Default Button Constants

Constant

Value

Default button

vbDefaultButton1

0

First button

vbDefaultButton2

256

Second button

vbDefaultButton3

512

Third button

vbDefaultButton4

768

Fourth button

Modality Constants

Constant

Value

modality

vbApplicationModal

0

Application

vbSystemModal

4096

System

  • The following intrinsic constants determine the action taken by the user and represent the value returned by the MsgBox function:

Return Values

Constant

Value

Button clicked

vbOK

1

OK

vbCancel

2

Cancel (or Esc key pressed)

vbAbort

3

Abort

vbRetry

4

Retry

vbIgnore

5

Ignore

vbYes

6

Yes

vbNo

7

No

  • If the MsgBox contains a Cancel button, the user can press the Esc key, and the function's return value is that of the Cancel button.
  • The Help button doesn't itself return a value, because it doesn't close the MsgBox dialog. If the user clicks the Help button, a Help window is opened. Once the Help window is closed, the user clicks one of the other buttons on the message box to close the dialog; this then returns a value.

Programming Tips and Gotchas

  • Application modality means that the user can't access other parts of the application until a response to the message box has been given. In other words, the appearance of the message box prevents the application from performing other tasks or from interacting with the user other than through the message box.
  • System modality used to mean that all applications were suspended until a response to the message box was given. However, with multitasking operating systems such as the Windows family of 32- and 64-bit operating systems, this isn't the case. Basically the message box is defined to be a "Topmost" window that is set to "Stay on Top," which means that the user can switch to another application and use it without responding to the message box; but because the message box is the topmost window, it's positioned on top of all other running applications.
  • Unlike its InputBox counterpart, MsgBox can't be positioned on the screen; it's always displayed in the center of the screen.
  • Since it produces a user interface that is displayed on the server rather than on the client, MsgBox should not be used within an ASP script that runs on the server. It can, however, be included as script in the text stream that an ASP page sends to the client.
  • If WSH scripts are run in batch mode (that is, with the /B switch), calls to the MsgBox function are ignored. Note that, if the return value of the MsgBox function is used to define the value of variables or to control program flow, the script may no longer function as intended when run in batch mode.

VBA/VBScript Differences

In VBA, if the title parameter is omitted, the name of the current application or project is displayed in the title bar. In VBScript, the string that appears on the title bar depends on the type of script that executes.

See Also

InputBox Function

Now Function  

Syntax

Now

Return Value

A Date.

Description

Returns the current date and time based on the system setting.

Example

The following example returns the date 10 days from today:

Dim dFutureDate
dFutureDate = DateAdd("d", 10, Now)

Programming Tips and Gotchas

  • It's often overlooked that workstations in a modern Windows environment are at the mercy of the user! If your application relies on an accurate date and time setting, you should consider including a line in the workstation's logon script to synchronize the time with one of the servers. Many so-called bugs have been traced to a workstation that has had its date or time wrongly altered by the user. The following line of code, when added to the logon script of an NT/Windows 2000 machine, synchronizes the machine's clock with that of a server called NTSERV1:

    net time \NTSERV1 /set
  • If you convert the date returned by Now to a string, it takes the Windows General Date format based on the locale settings of the local computer. The U.S. setting for General Date is mm/dd/yy hh:mm:ss.
  • The Now function is often used to generate timestamps. However, for short-term timing and intra-day timestamps, the Timer function, which returns the number of milliseconds elapsed since midnight, affords greater precision.

See Also

Timer Function

Oct Function  

Syntax

Oct(number)

number

Use: Required

Data Type: Numeric or String

Number or string representation of a number to convert.

Return Value

A String.

Description

Returns a string containing the octal representation of a given number.

Rules at a Glance

  • If number isn't already a whole number, it's rounded to the nearest whole number before being evaluated.
  • If number is Null, Oct returns Null.
  • If number is the special Empty variant, Oct returns 0 (zero).
  • Oct returns up to 11 octal characters.

Programming Tips and Gotchas

You can also use literals in your code to represent octal numbers by appending &O to the relevant octal value. For example, 100 decimal has the octal representation &O144. The following statement assigns an octal value to a variable:

lngOctValue1 = &o200  ' Assigns 128

See Also

Hex Function

On Error Statement  

Syntax

On Error Resume Next
On Error Goto 0

Description

Enables or disables error handling within a procedure. If you don't use an On Error statement in your procedure, or if you have explicitly switched off error handling, the VBScript runtime engine handles the error automatically. First, it displays a dialog containing the standard text of the error message, something many users are likely to find incomprehensible. Second, it terminates the application, so any error that occurs in the procedure produces a fatal runtime error.

Rules at a Glance

  • When a runtime error occurs in the routine in which the On Error Resume Next statement occurs, program execution continues with the program line following the line that generated the error. This means that, if you want to handle an error, this line following the line that generated the error should call or include an inline error-handling routine.
  • When a runtime error occurs in any routine called by the routine in which the On Error Resume Next statement occurs, or by its subroutines, program execution returns to the statement immediately after the subroutine call in the routine containing the On Error Resume Next statement.
  • When used in an ASP page for IIS 5.0, On Error Resume Next disables ASP's own error handling.
  • You disable error handling by using the On Error Goto 0 statement.

Programming Tips and Gotchas

  • If you have no error handling in your procedure, the VBScript runtime engine traces back through the call stack until a procedure is reached where error handling is enabled. In this case, the error is handled by that procedure by executing the statement immediately after the call to the subroutine that caused program control to leave the procedure. However, if no error handler can be found in the call stack, a runtime error occurs, and program execution is halted.
  • On Error Resume Next can be useful in situations where you are certain that errors will occur, or where the errors that could occur are minor. The following example shows how you can quickly cycle through an array with some uninitialized values to sum its elements. By using the On Error Resume Next statement, you force your program to ignore errors caused by elements with invalid data and carry on with the next element. For example, the following code fragment allows you to ignore errors caused by attempting to add nonnumeric data:

    On Error Resume Next
    Dim arr, element, sum
    arr = array(12, "string", 14, 7, 19, 2)
    
    For Each element in arr
     sum = sum + element
    Next
  • The quality of error trapping, error handling, and error reporting within a program often determines the success or failure of the application. Attention to detail in this area can be the difference between a stable, well-behaved, and robust application and one that seems to generate nothing but hassle. Using logs like the application and event logs in Windows NT, Windows 2000, and Windows XP within your error-handling routines can help you track down persistent problems quickly and efficiently. See Chapter 4, which explains creation of robust VBScript error-handling routines.
  • It's important to understand the flow of program control in the event an error occurs in a subroutine, and in particular, to understand that in the event of an error in a called routine, program execution returns to the statement after the statement that caused program flow to leave the routine containing the On Error Resume Next statement. In most cases, this behavior is highly undesirable. It can be prevented by including an On Error Resume Next statement in each routine of a script or module.
  • You can provide inline error handling after lines of code that are particularly likely to cause errors. Typically, this is done by checking whether the Err object's Number property is nonzero, as in the following code fragment:

    On Error Resume Next
    
    Dim oDAO 
    
    Set oDAO = CreateObject("DAO.DBEngine.30")
    If Err.Number <> 0 Then
     MsgBox Err.Number & ": " & Err.Description 'Handle error
    Err.Clear
    End If

    Note that it's particularly important to test for a nonzero error code rather than a positive error code, since most errors are unsigned long integers that VBScript (which does not support unsigned integers) represents as negative numbers. It's also important, once you've handled the error, to clear the error information by calling the Err object's Clear method.

  • You cannot trap syntax errors with the On Error statement. This is because syntax errors do not terminate a program; a program with syntax errors never even begins execution.

VBA/VBScript Differences

Unlike VBA, which also supports the On Error Goto syntax to branch program flow to an error-handling section within a routine or function, VBScript supports only the On Error Resume Next statement. This means that, if you're programming with VBScript, you must use inline error handling.

See Also

Err Object, Chapter 6

Option Explicit Statement  

Syntax

Option Explicit

Description

Use Option Explicit to generate an error whenever a variable that has not been declared is encountered.

Rules at a Glance

  • The Option Explicit statement must appear in a script before any other statements; otherwise, a nontrappable error occurs.
  • In modules where the Option Explicit statement isn't used, any undeclared variables are declared automatically.
  • Where Option Explicit is used, all variables must be declared using the Dim, Private, Public, or ReDim statements.

Programming Tips and Gotchas

  • It's considered good programming practice to always use the Option vbCrLfExplicit statement. The following example shows why:

     Dim iVariable
     
     iVariable = 100
     iVariable = iVarable + 50
     MsgBox iVariable

    In this code snippet, a variable, iVariable, has been declared. However, because the name of the variable has been mistyped in line 3, the message box shows its value as 50 instead of 150. This is because iVarable is assumed to be an undeclared variant whose value is 0. If the Option Explicit statement had been used, the code wouldn't have executed without generating an error, and iVarable would have been highlighted as the cause when Error 500, "Variable is undefined," was raised.

  • For ASP pages, the Option Explicit statement must appear before the beginning of the HTML stream. For example:

    <% Option Explicit %>
    

    A single Option Explicit statement applies to all script blocks in an ASP page.

Private Statement  

Syntax

Private varname[([subscripts])] [, varname[([subscripts])] . . .

varname

Use: Required

Variant Type: Any

The name of the variable, following Visual Basic naming conventions.

subscripts

Use: Optional

Variant Type: Integer or Long

Denotes varname as an array and optionally specifies the number and extent of array dimensions.

Description

Used in a script or in a class to declare a private variable and allocate the relevant storage space in memory.

Rules at a Glance

  • A Private variable's visibility is limited to the script in which it's created for global variables and to the class in which it is declared for class-level variables. Elsewhere, the Private keyword generates an error.
  • varname follows standard VB naming conventions. It must begin with an alphabetic character, can't contain embedded periods or spaces, can't be the same as a VBScript reserved word, must be shorter than 255 characters, and must be unique within its scope.
  • You can override standard variable naming conventions by placing your variable name in brackets. This allows you to use reserved words or illegal characters in variable names. For example:

    Private [me]
    Private [1Var]
    Private [2-Var]
  • The subscripts argument has the following syntax:

    upperbound [,upperbound]...

    For example:

    Private strNames(10)

    defines an array of 11 elements (an array whose lower bound is 0 and whose upper bound is 10). Similarly:

    Private lngPrices(10, 10)

    defines a two-dimensional array of eleven elements in each dimension.

  • Using the subscripts argument, you can declare up to 60 multiple dimensions for the array.
  • If the subscripts argument isn't used (i.e., the variable name is followed by empty parentheses), the array is declared dynamic. You can change both the number of dimensions and the number of elements of a dynamic array using the ReDim statement.
  • VBScript supports only the variant data type: all variables are variants. The following table shows the values held by each type of variant when it is first initialized:

Variable type

Initial value

Example

Array

Variant( )

Private arrNames(10)

Array Element

Empty

arr(0)

Variant Variable

Empty

Private vCtr

Programming Tips and Gotchas

  • The behavior of variables defined using the Private statement outside of a class is determined by the host. In general, there is rarely a good reason to declare a private variable outside of a class.
  • Within a class, you should prevent variables from being modified outside of the class by declaring them as private. Instead, public properties should be used to provide a means of accessing and modifying private variables. For example, rather than defining a public variable Age as follows:

    Class Person
     Dim Age
    End Class
  • You can define it as follows and allow properties to provide access to the private data:

    Class Person
     Dim iAge
    
     Public Property Get Age()
     Age = iAge
     End Property
    
     Public Property Let Age(value)
     iAge = value
     End Property
    End Class
  • One of the uses of private variables is in client-side scripts for IE. If there are multiple script blocks in a single page, a private variable is visible only in the script block in which it is declared; it is not visible in any other script block on that page.
  • All variables created at procedure level (that is, in code within a Sub...End Sub, Function...End Function, or Property...End Property construct are local by default. That is, they don't have scope outside the procedure in which they are created. The use of the Private keyword in these cases generates a runtime error.
  • You cannot change the dimensions of arrays that were defined to be dynamic arrays while preserving their original data.
  • It's good practice to always use Option Explicit at the beginning of a module to prevent misnamed variables from causing hard-to-find errors.

VBA/VBScript Differences

  • In VBA, you can explicitly define the lower bound of an array in the subscripts argument. In VBScript, this is not permitted; the lower bound of all arrays is always 0.
  • VBA supports the WithEvents keyword to allow an object reference to receive notification of the events fired by its corresponding object. VBScript, however, does not support the WithEvents keyword. Note, though, that some scriptable applications (such as Windows Script Host, Internet Explorer, and Active Server Pages) do expose their events to scripts.
  • VBA supports the New keyword to create early bound objects. However, since scripting languages necessarily rely on late binding, the New keyword is not supported in a variable declaration statement.

See Also

Dim Statement, Public Statement, ReDim Statement, Set Statement

Property Get Statement  

Syntax

[Public [Default] | Private Property Get name [(arglist)]
 [statements]
 [name = expression]
 [Exit Property] 
 [statements]
 [name = expression]
End Property

Public

Use: Optional

Type: Keyword

Makes the property accessible from outside the class, giving it visibility through all procedures in all scripts. Public and Private are mutually exclusive.

Default

Use: Optional

Type: Keyword

Used only with the Public keyword to indicate that a public property is the default property of the class.

Private

Use: Optional

Type: Keyword

Restricts the visibility of the property to those procedures within the same Class...End Class code block. Public and Private are mutually exclusive.

name

Use: Required

The name of the property.

arglist

Use: Optional

Data Type: Any

A comma-delimited list of variables to be passed to the property as arguments from the calling procedure.

statements

Use: Optional

Program code to be executed within the property.

expression

Use: Optional

Variant Type: Any

The value to return from the property to the calling procedure.

arglisthas the following syntax:

[ByVal | ByRef] argname[( )]

ByVal

Use: Optional

The argument is passed by value; that is, a local copy of the variable is assigned the value of the argument.

ByRef

Use: Optional

The argument is passed by reference; that is, the local variable is simply a reference to the argument being passed. Changes made to the local variable are reflected in the argument. ByRef is the default way of passing variables.

argname

Use: Required

The name of the local variable representing the argument.

Description

Declares the name, arguments, and code for a procedure that reads the value of a property and returns it to the calling procedure. The Property Get statement is used within a class defined by the Class...End Class construct.

Rules at a Glance

  • Property procedures are Public by default.
  • The Default keyword indicates that this Property Get procedure is the class's default member. A default member is automatically executed in an assignment statement without the need to explicitly reference it. To take a common example, the following two statements are identical:

    Set oCDrive = FileSystemObject.Drives.Item("C")
    Set oCDrive = FileSystemObject.Drives("C")

    Both return a reference to a Drive object representing the local system's C drive. The second statement works because Item is the default member of the Drives collection.

  • A class can have only a single default member. This must be a public procedure defined either by the Property Get statement or by the Function statement.
  • Unlike other function and procedure names, the name of the PropertyGetprocedure doesn't have to be unique within its class module. Specifically, the PropertyLet and PropertySet procedures can have the same name as the PropertyGet procedure. For example:

    Property Let Name(sVal)
     msName = sVal
    End Property
    
    Property Get Name( )
     Name = msName
    End Property
  • The number of arguments passed to a Property Get statement must match the corresponding Property Let or Property Set statement. For example:

    Public Property Let MyProperty(sVal, iVal)
     miMyProperty = iVal
    End Property
    
    Public Property Get MyProperty(sVal)
     MyProperty = miMyProperty
    End Property

    Both the PropertyLet and PropertyGet procedures share a common argument, sVal. The PropertyLet procedure has one additional argument, iVal, which represents the value that is to be assigned to the MyProperty property. (For details, see the next point.)

  • In a PropertyLet procedure, the last argument defines the data assigned to the property. The data returned by the PropertyGet procedure must match the last argument of a corresponding PropertyLet or PropertySet procedure.
  • If an Exit Property statement is executed, the property procedure exits and program execution immediately continues with the statement from which the property procedure was called. Any number of Exit Property statements can appear in a PropertyGet procedure.
  • If the value of the PropertyGet procedure has not been explicitly set when the program execution exits the procedure, its value will be empty, the uninitialized value of a variant.

Programming Tips and Gotchas

  • You can create a read-only property by defining a PropertyGet procedure without a corresponding PropertyLet or PropertySet procedure.
  • If the value of the property is an object, be sure to use the Set keyword when the Property Get procedure is called. For example:

    Property Get Drive
     Set Drive = oDrive
    End Property
  • You should protect the value of properties by defining a Private variable to hold the internal property value and control the updating of the property by outside applications through the Property Let and Property Get statements, as the following template describes:

    Class Object
     'Class Module Declarations Section
     'private data member only accessible from within 
     'this code module
     Private miMyProperty
    
     Public Property Let MyProperty(iVal)
     'procedure to allow the outside world to
     'change the value of private data member
     miMyProperty = iVal
     '(do not use a Property Let when creating a 
     'Read-Only Property)
     End Property
    
     Public Property Get MyProperty( ) As Integer
     'procedure to allow the outside world to
     'read the value of private data member
     MyProperty = miMyProperty
     End Property
    End Class

    Otherwise, if the variable used to store a property value is public, its value can be modified arbitrarily by any application that accesses the class containing the property.

  • Using a Property Let procedure rather than allowing the user to access a class variable directly allows you to perform validation on incoming data. For example, the following code insures that the value assigned to the Age property is a number that is between 0 and 110:

    Class Person
     Private iAge
    
     Property Get Age
     Age = iAge
     End Property
     Property Let Age(value)
     ' Check that data is numeric
     If Not IsNumeric(value) Then
     Err.Raise 13 ' Type mismatch error
     Exit Property
     ' Check that number is in range
     ElseIf value < 0 Or value > 110 Then
     Err.Raise 1031 ' Invalid number error
     End If
    
     iAge = value
     End Property
    End Class
  • The default method of passing a parameter is ByRef, which means that any modifications made to a variable passed as an argument to the Property Get statement are reflected in the variable's value when control returns to the calling routine. If this behavior is undesirable, explicitly pass parameters by value using the ByVal keyword in arglist.
  • You can use only the property defined by the Property Get statement on the right side of a property assignment.

VBA/VBScript Differences

  • VBScript allows you to designate a particular PropertyGet procedure as the default member of its class. As of Version 6.0, VBA does not.
  • VBA supports Friend property procedures as well as public and private ones. VBScript supports only public and private property procedures.
  • VBA supports the Static keyword in the property declaration, which preserves the value of all local variables between calls to the PropertyGet procedure. VBScript does not have an Optional keyword to support optional arguments. "Optional arguments" in VBScript are supported only by omitting arguments to a procedure call. VBScript provides no way of assigning default values to optional arguments.
  • VBA supports optional parameters and allows them to be assigned a default value. VBScript does not support optional arguments.

See Also

Property Let Statement, Property Set Statement

Property Let Statement  

Syntax

[Public | Private Property Let name ([arglist,] value)
 [statements]
 [Exit Property] 
 [statements]
End Property

Public

Use: Optional

Type: Keyword

Makes the property visible outside of the class, giving it visibility through all procedures in all scripts. Public and Private are mutually exclusive.

Private

Use: Optional

Type: Keyword

Restricts the visibility of the property to those procedures within the same Class...End Class code block. Private and Public are mutually exclusive.

name

Use: Required

The name of the property.

arglist

Use: Optional

Data Type: Any

A comma-delimited list of variables to be passed to the property as arguments from the calling procedure.

value

Use: Required

Data Type: Any

The last (or only) argument in arglist; a variable containing the value to be assigned to the property.

statements

Use: Optional

Program code to be executed within the property.

arglist uses the following syntax:

[ByVal | ByRef] varname[( )]

ByVal

Use: Optional

Type: Keyword

The argument is passed by value; that is, a local copy of the variable is assigned the value of the argument.

ByRef

Use: Optional

Type: Keyword

The argument is passed by reference; that is, the local variable is simply a reference to the argument being passed. All changes made to the local variable are reflected in the calling argument when control returns to the calling procedure. ByRef is the default method of passing variables.

varname

Use: Required

The name of the local variable containing either the reference or value of the argument.

Description

Declares the name, arguments, and code for a procedure that assigns a value to a property. The Property Let statement is used within a class defined by the Class...End Class construct.

Rules at a Glance

  • A Property Let statement must contain at least one argument in arglist. If there is more than one argument, the last one contains the value to be assigned to the property. (This is the argument indicated as value in the prototype for the Property Let statement.)
  • The last argument in arglist should correspond to both the private data member (at least, it should be defined as Private; see the first comment in the "Programming Tips and Gotchas" section) used to hold the property value and the return value of the corresponding Property Get procedure, if there is one.
  • Property procedures are Public by default.
  • Unlike other functions and procedures, the name of the Property Let procedure can be repeated within the same module as the name of the Property Get and Property Set procedures.
  • The number of the arguments passed to a Property Let statement must match the corresponding Property Get statement. For details, see the section "Rules at a Glance" in the entry for Property Get.
  • If an Exit Property statement is executed, program flow continues with the statement following the call to the property. Any number of Exit Property statements can appear in a Property Let procedure.

Programming Tips and Gotchas

  • You should protect the values of properties by defining a Private variable to hold the internal property value and control the updating of the property by outside applications via Property Let and Property Get statements, as described in the "Programming Tips and Gotchas" section of the Property Get statement.
  • You can create a write-only property by defining a Property Let procedure without a corresponding Property Get procedure. Write-only properties, however, are comparatively rare, and are used primarily to prevent access to sensitive information such as passwords.
  • The default method of passing parameters is ByRef, which means that any modifications made to a variable passed as an argument to the Property Let statement are reflected in the variable's value when control returns to the calling routine. If this behavior is undesirable, explicitly pass arguments by value using the ByVal keyword in arglist.
  • You can use the property defined by the Property Let statement only on the left side of a property assignment.

VBA/VBScript Differences

  • VBA supports Friend property procedures as well as public and private ones. VBScript supports only public and private property procedures.
  • VBA supports the Static keyword in the property declaration, which preserves the value of all local variables between calls to the Property Let procedure. VBScript does not have an Optional keyword to support optional arguments. "Optional arguments" in VBScript are supported only by omitting arguments to a procedure call. VBScript provides no way of assigning default values to optional arguments.
  • VBA supports optional parameters and allows them to be assigned a default value. VBScript does not support optional arguments.

See Also

Property Get Statement

Property Set Statement  

Syntax

[Public | Private Property Set name ([arglist,] reference)
 [statements]
 [Exit Property] 
 [statements]
End Property

Public

Use: Optional

Type: Keyword

Makes the property accessible from outside the class, so that it is visible to all procedures in all scripts. Public and Private are mutually exclusive.

Private

Use: Optional

Type: Keyword

Restricts the scope of the property to code within the Class...End Class construct in which the property is declared. Public and Private are mutually exclusive.

name

Use: Required

The name of the property.

arglist

Use: Optional

Data Type: Any

A comma-delimited list of variables to be passed to the property as arguments from the calling procedure.

reference

Use: Required

Data Type: Object

The last (or only) argument in arglist, it must be a variable containing the object reference to be assigned to the property.

statements

Use: Optional

Program code to be executed within the property.

arglist uses the following syntax and parts:

[ByVal | ByRef] varname[( )] _

ByVal

Use: Optional

Type: Keyword

The argument is passed by value; that is, a local copy of the variable is assigned the value of the argument.

ByRef

Use: Optional

Type: Keyword

The argument is passed by reference; that is, the local variable is simply a reference to the argument being passed. All changes made to the local variable are reflected in the calling argument when control returns to the calling procedure. ByRef is the default method of passing variables.

varname

Use: Required

Data Type: Any

The name of the local variable containing either the reference or value of the argument.

Description

Declares the name, arguments, and code for a procedure that assigns an object reference to a property. The Property Set statement is used within a class defined by the Class...End Class construct.

Rules at a Glance

  • A Property Set statement must contain at least one argument in arglist. (This is the argument indicated as reference in the statement's prototype.) If there is more than one argument, it's the last one that contains the object reference to be assigned to the property.
  • The last argument in arglist must match both the private data member used to hold the property value and the data returned by the corresponding Property Get procedure, if there is one.
  • Property procedures are Public by default.
  • Unlike other variables and procedures, the name of a Property Set procedure can be repeated within the same module as the name of a Property Get procedure.
  • The number of arguments passed to a Property Set statement must match the corresponding Property Get statement. For example:

    Public Property Set MyProperty(iVal, oVal)
     Set miMyProperty(iVal) = oVal
    End Property
    
    Public Property Get MyProperty(iVal)
     Set MyProperty = miMyProperty(iVal)
    End Property

    Both the Property Set and the Property Get procedures share a common argument, iVal. The Property Set procedure has one additional argument, oVal, which represents the object that is to be assigned to the MyProperty property.

  • If an Exit Property statement is executed, program execution immediately continues with the statement following the call to the property. Any number of Exit Property statements can appear in a Property Set procedure.

Programming Tips and Gotchas

  • You should protect the values of properties by defining a Private variable to hold the internal property value and control the updating of the property by outside applications via Property Set and Property Get statements, as described in the "Programming Tips and Gotchas" section of the entry for the Property Get statement.
  • The default method of passing parameters is ByRef, which means that any modifications made to a variable passed as an argument to the Property Set statement are reflected in the variable's value when control returns to the calling routine. If this behavior is undesirable, explicitly pass arguments by value using the ByVal keyword in arglist.
  • The property defined by the Property Set statement can occur only on the left side of a statement that assigns an object reference.

VBA/VBScript Differences

  • VBA supports Friend property procedures as well as public and private ones. VBScript supports only public and private property procedures.
  • VBA supports the Static keyword in the property declaration, which preserves the value of all local variables between calls to the Property Set procedure. VBScript does not have an Optional keyword to support optional arguments. "Optional arguments" in VBScript are supported only by omitting arguments to a procedure call. VBScript provides no way of assigning default values to optional arguments.
  • VBA supports optional parameters and allows them to be assigned a default value. VBScript does not support optional arguments.

See Also

Property Get Statement, Property Let Statement

Public Statement  

Syntax

Public varname[([subscripts])] _
 varname[([subscripts])]

varname

Use: Required

Data Type: Any

The name of the variable, which must follow VBScript naming conventions (see the second bullet in "Rules at a Glance").

subscripts

Use: Optional

Data Type: Integer or Long

Denotes varname as an array and optionally specifies the dimensions and number of elements of the array.

Description

Used in a script or a Class block to declare a public variable and allocate the relevant storage space in memory. A Public variable has global scopethat is, it can be used by all procedures in a script. When used in a class construct, it is visible outside the class project.

Rules at a Glance

  • The behavior of a Public variable depends on where it's declared, as the following table shows:

Variable declared in...

Scope

Any procedure, Function or Property statement

Illegal; generates a syntax error; use the Dim statement instead.

Global code

Variable is available throughout the script.

Class block declarations section

Variable is available as a property of the class to all code within the script.

  • You can override standard variable naming conventions by placing your variable name in brackets. This allows you to use reserved words or illegal characters in variable names. For example:

    Public [me]
    Public [1Var]
    Public [2-Var]
  • varname follows standard VB naming conventions. It must begin with an alphabetic character, can't contain embedded periods or spaces, can't be the same as a VBScript reserved word, must be shorter than 255 characters, and must be unique within its scope.
  • The subscripts argument has the following syntax:

    upperbound [, upperbound]
  • Using the subscripts argument, you can declare up to 60 dimensions for the array.
  • If the subscripts argument isn't used (i.e., the variable name is followed by empty parentheses), the array is declared as dynamic. You can change both the number of dimensions and number of elements of a dynamic array using the ReDim statement.
  • All variables are variants. The following table shows the values held by each type of variant when it is first initialized:

Data type

Initial value

Example

Array

Variant( )

Public arrNames(10)

Array Element

Empty

arr(0)

Scalar Variable

Empty

Public vCtr

Programming Tips and Gotchas

  • The precise meaning of a public variable is defined by the host environment. In Internet Explorer, a variable defined as public in a script block is visible in all other script blocks on the page, including those written in JScript.
  • Instead of declaring a variable as Public within a class construct, you should create Property Let and Property Get procedures that assign and retrieve the value of a private variable, respectively.
  • You cannot change the dimensions of arrays that were not defined to be dynamic arrays.
  • It's good programming practice to always use Option Explicit at the beginning of a module to prevent misnamed variables causing hard-to-find errors.

VBA/VBScript Differences

  • In VBA, you can explicitly define the lower bound of an array in the subscripts argument. In VBScript, this is not permitted; the lower bound of all arrays is always 0.
  • VBA supports the WithEvents keyword to allow an object variable to receive notification of the events fired by the object to which it refers. VBScript, however, does not support the WithEvents keyword. Note, though, that some scriptable applications (such as Windows Script Host, Internet Explorer, and Active Server Pages) do expose their events to scripts.
  • VBA supports the New keyword to create early bound objects. However, since scripting languages necessarily rely on late binding, the New keyword is not supported in a variable declaration statement.

See Also

Private Statement, ReDim Statement, Set Statement

Randomize Sub  

Syntax

Randomize [number]

number

Use: Optional

Data Type: Numeric

Any valid numeric expression.

Description

Initializes the random number generator.

Rules at a Glance

  • Randomize uses number as a new seed value to initialize the random number generator used by the Rnd function. The seed value is an initial value that generates a sequence of pseudorandom numbers.
  • If you don't pass number to the Randomize statement, the value of the system timer is used as the new seed value.
  • Repeatedly passing the same number to Randomize doesn't cause Rnd to repeat the same sequence of random numbers.
  • If Randomize is not used and the Rnd function is called either with no argument or with 1 as an argument, the Rnd function always uses the same number as the seed value the first time it is called, and subsequently uses the last generated number as a seed value.

Programming Tips and Gotchas

If you need to repeat a sequence of random numbers, you should call the Rnd function with a negative number as an argument immediately prior to using Randomize with any numeric argument. This is illustrated in the example program.

Example

RepeatNumbers()

Sub RepeatNumbers()
 Dim arr(9, 3)
 Dim loopCtr, intCtr
 Dim strMsg

 For loopCtr = 0 To 3
 Rnd -1
 Randomize(100)
 For intCtr = 0 To 9
 strMsg = strMsg & Rnd() & " "
 Next
 strMsg = strMsg & vbCrLf
 Next

 MsgBox strMsg
End Sub

See Also

Rnd Function

ReDim Statement  

Syntax

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

Preserve

Use: Optional

Type: Keyword

Preserves the data within an array when changing its single or its last dimension.

varname

Use: Required

Data Type: Any

Name of the variable.

subscripts

Use: Required

Number of elements and dimensions of the array, using the following syntax:

upper [, upper] . . .

where upper is the upper bound of a particular array dimension.

Description

Used within a procedure to resize and reallocate storage space for a dynamic array.

Rules at a Glance

  • A dynamic array is created using a Private, Public, or Dim statement with empty parentheses. Only dynamic arrays created in this manner can be resized using the ReDim statement. There is no limit to the number of times you can redimension a dynamic array.
  • Use of the Preserve keyword allows you to retain the current values within the array, but it also places several limitations on how the Redim statement can be used:

    • Only the last dimension of an array can be resized.
    • The number of dimensions can't be changed.
    • Only the upper bound of the array can be changed.
  • If you reduce either the number of elements of the array or the number of dimensions in the array, data in the removed elements is permanently lost, irrespective of the use of the Preserve keyword.

Programming Tips and Gotchas

  • You can pass an array by reference to a procedure, redimension it within the procedure, and return the modified array to the calling program. This is illustrated in the following code:

    CreateArray( )
    
    Private Sub CreateArray( )
    
     Dim strArray( ), strElement, strMsg
     Dim intCtr 
     
     ReDim strArray(9)
     
     For intCtr = 0 To UBound(strArray)
     strArray(intCtr) = "Original element"
     Next
     
     ExpandArray strArray
     
     For intCtr = 0 To UBound(strArray)
     strMsg = strMsg & strArray(intCtr) & vbCrLf
     Next
    
     MsgBox strMsg
     
    End Sub
    
    Private Sub ExpandArray(ByRef arrDynamic( ))
    
     Dim intBound, intCtr
     
     intBound = UBound(arrDynamic)
     
     ReDim Preserve arrDynamic(UBound(arrDynamic) * 2)
     
     For intCtr = intBound + 1 To UBound(arrDynamic)
     arrDynamic(intCtr) = "New element"
     Next
    
    End Sub

    When you run this example, both the original elements and new elements are listed in a message box, proving that the array was successfully expanded in the ExpandArray procedure.

  • It's possible to create a new dynamic array within a procedure using the ReDim statement if the array to which it refers doesn't already exist. Typically, this results from an error of omission; the programmer forgets to explicitly define the array using Dim, Public, or Private. Since this method of creating an array can cause conflicts if a variable or array of the same name is subsequently defined explicitly, ReDim should be used only to redimension an existing array, not to define a new one.
  • When a dynamic array is initialized, its individual elements are Empty. You can determine whether a value has been assigned to a particular element by using the IsEmpty function.

VBA/VBScript Differences

VBA allows you to define the lower limit of a redimensioned array as well as its upper limit. Arrays in VBScript, on the other hand, are always zero-based.

See Also

Dim Statement, Private Statement, Public Statement

RegExp Object  

Description

The RegExp object provides support for regular expression matchingfor the ability to search strings for substrings matching general or specific patterns.

In order to conduct a pattern search, you must first instantiate the regular expression object, with code like the following:

Dim oRegExp ' Instance of RegExp object 
Set oRegExp = New RegExp

To conduct a search using the RegExp object, do the following:

  • Determine whether the search should be case-sensitive.
  • Determine whether all instances or just the first instance of the substring should be returned.
  • Supply the pattern string that you want to find.
  • Provide a string that the RegExp object is to search.

The RegExp object allows you to search for a substring that matches your pattern string in any of three ways:

  • You can determine whether a pattern match is found in the string.
  • You can return one or all of the occurrences of the matching substrings. In this case, results are returned in Match objects within the Matches collection.
  • You can replace all substrings matching the pattern string with another string.

Properties

The RegExp object supports the three properties shown in the following table. Each is documented in depth in its own section in the Language Reference.

Property name

Description

Global

Indicates whether to search for all occurrences of the pattern string or just for the first one

IgnoreCase

Indicates whether the pattern search is case-sensitive

Pattern

Indicates the pattern string to search for

Methods

The RegExp object supports the three methods shown in the following table. Each is documented in depth in its own section in the Language Reference.

Method name

Description

Execute

Returns a Matches collection containing information about the substrings in a larger string that match a pattern string

Replace

Replaces all substrings in a larger string that match a pattern string with a second string

Test

Indicates whether the search of a string has succeeded in finding a pattern match

VBA/VBScript Differences

The RegExp object, which was introduced to give VBScript comparable features to JScript, is exclusive to VBScript; it does not exist as a core part of the VBA language. However, the RegExp object is implemented as a member of the VBScript.dll library and can be added to any Visual Basic project. It is listed in the References dialog (which is available by selecting the References option from the Visual Basic Project menu) as "Microsoft VBScript Regular Expressions."

See Also

InStr, InStrB Functions, InstrRev Function, Match Object, Matches Collection Object

RegExp.Execute Method  

Syntax

RegExp.Execute(string)

string

Use: Required

Data Type: String

The string to be searched.

Return Value

A Matches collection containing one or more Match objects.

Description

Performs a regular expression search against string and returns the results in the Matches collection.

Rules at a Glance

  • The method searches string using the RegExp object's Pattern property.
  • The results are returned in the Matches collection, which is a collection of Match objects.
  • If the search finds no matches, the Matches collection is empty.

Programming Tips and Gotchas

  • Remember to use the Set statement to assign the Matches collection returned by the Execute method to an object variable.
  • You can determine whether the Matches collection returned by the Execute method is empty by examining its Count property. It is empty if the value of Count is 0.

Example

See the example for the RegExp.Pattern Property.

See Also

Matches Collection Object, RegExp.Pattern Property, RegExp.Replace Method, RegExp.Test Method

RegExp.Global Property  

Data Type

Boolean

Description

Determines whether the search for a pattern string should match all occurrences in the search string or just the first one.

Rules at a Glance

A search will attempt to locate only the first occurrence of the pattern string in a search string; that is, the default value of the Global property is False. If you want to search for all occurrences of the pattern string in the search string, you must set the Global property to True.

Programming Tips and Gotchas

If you're interested only in determining whether the pattern string exists in the search string, there's no point in overriding the Global property's default value of False.

See Also

Matches Collection Object, Match Object, RegExp Object

RegExp.IgnoreCase Property  

Data Type

Boolean

Description

Determines whether the search for a pattern string is case-sensitive.

Rules at a Glance

By default, regular expression searches are case-sensitive; that is, the default value of the IgnoreCase property is False. If you don't want the search to be case-sensitive, you must set the IgnoreCase property to True.

Programming Tips and Gotchas

If your search string does not attempt to match any alphabetic characters (A-Z and a-z), you can safely ignore the setting of IgnoreCase, since it won't affect the results of your search.

See Also

RegExp Object, RegExp.Pattern Property

RegExp.Pattern Property  

Data Type

String

Description

Contains a pattern string that defines the substring to be found in a search string.

Rules at a Glance

The following table defines the meaning of the individual characters that can be included in the pattern string. The table in the "Programming Tips and Gotchas" section lists a pattern string using each symbol and shows the results returned by the Execute method.

Symbol

Description

Marks the next character as either a special character (such as for the newline character) or as a literal (if that character otherwise has special meaning in a pattern search string). The special characters are:

f

form feed character

newline character

carriage return character

tab character

v

vertical tab character

^

Matches the beginning of input.

$

Matches the end of input.

*

Matches the preceding atom zero or more times.

+

Matches the preceding atom one or more times.

?

Matches the preceding atom zero or one time.

.

Matches any single character except a newline character.

( )

Defines a subexpression within the larger subexpression. A subexpression:

  • Overrides the order of precedence used in evaluating pattern strings.
  • Can be referenced again in the pattern string. To insert the result of the subexpression later in the pattern string, reference it by its one-based ordinal position among subexpressions, preceded by the backslash symbol (e.g., 1). See the example using the um syntax in the "Programming Tips and Gotchas" section.
  • Can be referenced again in the replacement string in calls to the RegExp.Replace method. To use the result of the original subexpression as a replacement string, reference its one-based ordinal position among subexpressions, preceded by a dollar sign (e.g., $1). See RegExp.Replace Method for an example.

x|y

Matches either x or y.

{n}

Matches exactly n times, where n is a nonnegative integer.

{n,}

Matches at least n times, where n is a nonnegative integer. o{1,} is the same as o+, and o{0,} is the same as o*.

{n,m}

Matches at least n and at most m times, where m and n are nonnegative integers. o{0,1} is the same as o?.

[abc]

Matches any one of the enclosed characters (represented by abc) in the character set.

[^xyz]

Matches any character (represented by xyz) not enclosed in the character set. For example, [^abc] matches the "p" in "plain."

[a-z]

Matches any character in a range of characters (represented by a-z).

[^m-z]

Matches any character not included in a range of characters (represented by m-z).



Matches a word boundary; that is, the position between a word and a space. The word boundary symbol does not include newline characters or the end of input (see the s symbol).

B

Matches a nonword boundary. ea*rB matches the "ear" in "never early."

d

Matches a digit character. Equivalent to [0-9].

D

Matches a nondigit character. Equivalent to [^0-9].

s

Matches any whitespace, including space, tab, form-feed, etc. Equivalent to [ f v].

S

Matches any nonwhitespace character. Equivalent to [^ f v].

w

Matches any word character including underscore. Equivalent to [A-Za-z0-9_].

W

Matches any nonword character, including whitespace and carriage returns. Equivalent to [^A-Za-z0-9_].

um

Matches the subexpression (enclosed in parentheses) whose ordinal position in the pattern is num, where num is a positive integer.

Matches n, where n is the octal value of an ASCII code. Octal escape values must be 1, 2, or 3 digits long and must not exceed 256; if they do, only the first two digits are used.

xn

Matches n, where n is the hexadecimal value of an ASCII code. Hexadecimal escape values must be two digits long.

Programming Tips and Gotchas

The following table shows a search string and the Value property of each Match object returned by the Execute method when the string:

"To be or not to be. That is the question." & vbCrLf & _
"Whether 'tis nobler in the mind to endure..."

is passed to the Execute method. The RegExp object's Global property is set to True, and its IgnoreCase property is set to True.

Pattern

Matches

.....

Wheth

^.....

To be

.....$

re...

no*

no, n, no, n, n, n (6 matches)

no+

no, no (2 matches)

bo*e?

be, be, b (3 matches)

qu...

quest

th(at|e)

That, the, the, the (4 matches)

to|i

To, to, i, i, i, i, i, to (8 matches)

.{3}

...

.{2,}

...

.{1,3)

., ., ... (3 matches)

i[nst]

is, is, in, in (4 matches)

[^bhm]e

ue, le, e, re (4 matches)

[r-z]o

To, to, to (3 matches)

[^o-z]o

o, no, io, no (4 matches)

.o

To, to, to (3 matches)

.oB

o, no, io, no (4 matches)

d

(0 matches)

D.

e., n. (2 matches)

...s

be, not, be., hat, the, on., her, tis, ler, the, ind (11 matches)

S{3}

not, the, tis, the (3 matches)

w{3}.s

ion.

W{3}

. (vbCrLf), ... (2 matches)

(S+)(s+)S+2S+2S+2

To be or not, to be. That is, Whether `tis nobler in (3 matches)

164157

To, to, to (3 matches)

x74x6f

To, to, to (3 matches)

Searches using regular expressions can be quite complex. If you're interested in a book that deals exclusively with regular expressions and pattern searches, see Mastering Regular Expressions, written by Jeffrey E. Friedl (O'Reilly).

Example

The following routine allows you to experiment with searches using regular expressions. When you call it, just pass the string you'd like to search. A dialog appears repeatedly, prompting you for a pattern string, followed by another dialog that displays the results of the search using the regular expression you've entered. When you're finished, simply click the Cancel button to exit the routine:

Public Sub SearchExp(strSearch)

Dim oRegExp, colMatches, oMatch 
Dim strPattern

Set oRegExp = New RegExp

oRegExp.Global = True
oRegExp.IgnoreCase = True

Do 

 strPattern = InputBox("Enter pattern string: ", "Pattern", "")
 if strPattern = "" then
 Exit Do
 Else
 oRegExp.Pattern = strPattern
 end If
 strMsg = "Pattern: " & oRegExp.Pattern 
 
 Set colMatches = oRegExp.Execute(strSearch)
 strMsg = strMsg & ", Matches: " & colMatches.Count & vbcrlf & vbcrlf
 if colMatches.Count > 0 Then
 for each oMatch in colMatches
 strMsg = strMsg & oMatch.Value & vbCrLf
 next
 Else
 strMsg = strMsg & "No match found"
 End If

 MsgBox strMsg

Loop

End Sub

See Also

RegExp Object, RegExp.Execute Method, RegExp.Replace Method, RegExp.Test Method

RegExp.Replace Method  

Syntax

RegExp.Replace(searchString, replaceString)

searchString

Use: Required

Data Type: String

The string to be searched.

replaceString

Use: Required

Data Type: String

The replacement string.

Return Value

A String containing the entire string that results when matched substrings in searchString are replaced with replaceString.

Description

Performs a regular expression search against searchString and replaces matched substrings with replaceString.

Rules at a Glance

  • The method searches searchString using the RegExp object's Pattern property.
  • If no matches are found, the method returns searchString unchanged.

Programming Tips and Gotchas

replaceString the replacement string, can contain pattern strings that control how substrings in searchString should be replaced.

Example

The following WSH code illustrates the use of subexpressions in the search and replacement strings. The search returns three subexpressions: "to be", "or", and "not to be". The first subexpression is replaced with the third, while the third subexpression is replaced with the first, resulting in the string "not to be or to be":

Dim strString, strPattern, strReplace, strResult
Dim oRegExp

strString = "to be or not to be " 
strPattern = "(S+s+S+s+)(S+s+)(S+s+S+s+S+s+)"
strReplace = "$3$2$1"

Set oRegExp = New RegExp
oRegExp.Pattern = strPattern

strResult = oRegExp.Replace(strString, strReplace)
If strResult = strString Then
 MsgBox "No replacements were made"
Else
 MsgBox strResult
End If

See Also

RegExp.Execute Method, RegExp.Pattern Property, RegExp.Test Method

RegExp.Test Method  

Syntax

RegExp.Test(string)

string

Use: Required

Data Type: String

The string to be searched.

Return Value

A Boolean indicating whether a match was found.

Description

Performs a regular expression search against string and indicates whether a match was found

Rules at a Glance

  • Prior to calling the Test method, the search string should be defined by setting the Pattern property.
  • The method searches string using the RegExp object's Pattern property.
  • The method returns True if the search succeeds and False otherwise.

Programming Tips and Gotchas

  • Since a search is successful if one match is found, you do not have to set the RegExp object's Global property before calling the Test method.
  • You can use the method to determine whether a match exists before calling either the Execute or the Replace methods.

See Also

RegExp.Execute Method, RegExp.Pattern Property, RegExp.Replace Method

Rem Statement  

Syntax

Rem comment
' comment

comment

Use: Optional

A textual comment to place within the code.

Description

Use the Rem statement or an apostrophe (') to place remarks within the code.

Rules at a Glance

Apostrophes held within quotation marks aren't treated as comment markers, as this code snippet shows:

myVar = "'Something'"

VBA/VBScript Differences

  • In VBA, if you use the Rem statement (but not the apostrophe) on the same line as program code, a colon is required after the program code and before the Rem statement. For example:

    Set objDoc = Server.CreateObject("MyApp.MyObj") : Rem Define the object
     Rem reference

    VBScript, on the other hand, successfully recognizes the Rem statement even without the colon.

  • In VBA using the VBA editor, if you "comment out" a line, that line and all of its line continuations are affected. In VBScript, the comment keyword or symbol must be added to each line to be "commented out."
Replace Function  

Syntax

Replace(string, stringToReplace, replacementString [, start[, count[, 
compare]]])

string

Use: Required

Data Type: String

The complete string containing the substring to be replaced.

stringToReplace

Use: Required

Data Type: String

The substring to be found by the function.

replacementString

Use: Required

Data Type: String

The new substring to replace stringToReplace in string.

start

Use: Optional

Data Type: Long

The character position in string at which the search for stringToReplace begins.

count

Use: Optional

Data Type: Long

The number of instances of stringToReplace to replace.

compare

Use: Optional

Data Type: Integer

The method that compares stringToReplace with string ; its value can be vbBinaryCompare or vbTextCompare.

Return Value

The return value from Replace depends on the parameters you specify in the argument list, as the following table shows:

If

Return value

string = ""

Zero-length string ("")

string is Null

An error

StringToReplace = ""

Copy of string

replacementString = ""

Copy of string with all instances of stringToReplace removed

start > Len(string)

Zero-length string ("")

count = 0

Copy of string

Description

Replaces a given number of instances of a specified substring in another string.

Rules at a Glance

  • If start is omitted, the search begins at the start of the string.
  • If count is omitted, its value defaults to -1, which means that all instances of the substring after start are replaced.
  • vbBinaryCompare is case-sensitive; that is, Replace matches both character and case, whereas vbTextCompare is case-insensitive, matching only character, regardless of case.
  • The default value for compare is vbBinaryCompare.
  • start not only specifies where the search for stringToReplace begins, but also where the new string returned by the Replace function commences.

Programming Tips and Gotchas

  • If count isn't used, be careful when replacing short strings that may form parts of unrelated words. For example, consider the following:

    Dim sString
    sString = "You have to be careful when you do this " _
     & "or you could ruin your string"
    Msgbox Replace(sString, "you", "we")

    Because we don't specify a value for count, the call to Replace replaces every occurrence of "you" in the original string with "we." But the fourth occurrence of "you" is part of the word "your," which is modified to become "wer."

    The best way to avoid this problem is to use regular expressions. By specifying the word-break pattern in your search criterion, you can insure that only whole words are matched. For example:

    strSearch = "You have to be careful when you do this " _
     & "or you could ruin your string for you."
    
    oRegExp.Pattern = "you·"
    str = oRegExp.Replace(strSearch, "we")
    
    MsgBox str
  • You must also be aware that if start is greater than 1, the returned string starts at that character and not at the first character of the original string, as you might expect. For example, given the statements:

    sOld = "This string checks the Replace function"
    sNew = Replace(sOld, "check", "test", 5, _
     vbTextCompare)
    sNew will contain the value:
    "string tests the Replace function"

See Also

InStr, InStrB Functions, Mid, MidB Functions

RGB Function  

Syntax

RGB(red, green, blue)

red

Use: Required

Data Type: Integer

A number between 0 and 255, inclusive.

green

Use: Required

Data Type: Integer

A number between 0 and 255, inclusive.

blue

Use: Required

Data Type: Integer

A number between 0 and 255, inclusive.

Return Value

A Long integer representing the RGB color value.

Description

Returns a system color code that can be assigned to object color properties.

Rules at a Glance

  • The RGB color value represents the relative intensity of the red, green, and blue components of a pixel that produces a specific color on the display.
  • The RGB function assumes any argument greater than 255 is 255.
  • The following table demonstrates how the individual color values combine to create certain colors:

Color

Red

Green

Blue

Black

0

0

0

Blue

0

0

255

Green

0

255

0

Red

255

0

0

White

255

255

255

Programming Tips and Gotchas

  • The RGB value is derived with the following formula:

    RGB = red + (green * 256) + (blue * 65536)

    In other words, the individual color components are stored in the opposite order one would expect. VBScript stores the red color component in the low-order byte of the long integer's low-order word, the green color in the high-order byte of the low-order word, and the blue color in the low-order byte of the high-order word.

  • VBScript has a wide range of intrinsic color constants that can assign color values directly to color properties of objects. For a list of these, see Appendix B.
Right, RightB Functions  

Syntax

Right(string, length)

string

Use: Required

Data Type: String

The string to be processed.

length

Use: Required

Data Type: Long

The number of characters to return from the right of the string.

Return Value

A String.

Description

Returns a string containing the right-most length characters of string.

Rules at a Glance

  • If length is 0, a zero-length string (" ") is returned.
  • If length is greater than the length of string, string is returned.
  • If length is less than zero or is Null, an error is generated.
  • If string contains a Null, Right returns Null.

Example

The following function assumes it's passed either a filename or a complete path and filename, and returns the filename from the end of the string:

Private Function ParseFileName(strFullPath)

Dim lngPos, lngStart
Dim strFilename

lngStart = 1
Do
 lngPos = InStr(lngStart, strFullPath, "")
 If lngPos = 0 Then
 strFilename = Right(strFullPath, Len(strFullPath) - lngStart + 1)
 Else
 lngStart = lngPos + 1
 End If
Loop While lngPos > 0

ParseFileName = strFilename

End Function

Programming Tips and Gotchas

  • Use the Len function to determine the total length of string.
  • When you use the RightB function with byte data, length specifies the number of bytes to return.

VB/VBA Differences

Because VBScript doesn't support strong typing, it does not support the Right$ and RightB$ functions, which explicitly return a data type.

See Also

Len, LenB Functions, Left, LeftB Functions

Rnd Function  

Syntax

Rnd[(seed)]

seed

Use: Optional

Data Type: Single

Any valid numeric expression.

Return Value

A random number of variant type Single.

Description

Returns a random number.

Rules at a Glance

  • The behavior of the Rnd function is determined by seed, as described in this table:

Number

Rnd generates...

< 0

The same number each time, using seed as the seed number

> 0

The next random number in the current sequence

0

The most recently generated number

Not supplied

The next random number in the current sequence

  • The Rnd function always returns a value between and 1.
  • If number isn't supplied, the Rnd function uses the last number generated as the seed for the next generated number. This means that given an initial seed (seed), the same sequence is generated if number isn't supplied on subsequent calls.

Example

The following example uses the Randomize statement along with the Rnd function to fill 100 cells of an Excel worksheet with random numbers:

Public Sub GenerateRandomNumbers( )

Dim objExcel, objBook, objSheet
Dim intRow, intCol

' Start Excel
Set objExcel = CreateObject("Excel.Application")

' Get or create active worksheet
If objExcel.ActiveSheet Is Nothing Then
 Set objBook = objExcel.Workbooks.Add
End If 
Set objSheet = objExcel.ActiveWorkbook.ActiveSheet
Randomize

' make Excel visible
objExcel.Visible = True
' Set the color of the input text to blue
objSheet.Cells.Font.ColorIndex = 5 
' Loop through first 10 rows & columns, 
' filling them with random numbers
For intRow = 1 To 10
 For intCol = 1 To 10
 objSheet.Cells(intRow, intCol).Value = Rnd
 Next
Next
' Resize columns to accommodate random numbers
objSheet.Columns("A:C").AutoFit

End Sub

Programming Tips and Gotchas

  • Before calling the Rnd function, you should use the Randomize statement to initialize the random number generator.
  • The standard formula for producing numbers in a given range is as follows:

    Int((highest - lowest + 1) * Rnd + lowest)

    where lowest is the lowest required number in the range, and highest is the highest.

See Also

Randomize Sub

Round Function  

Syntax

Round(expression[, numdecimalplaces])

expression

Use: Required

Data Type: Numeric

Any numeric expression.

numdecimalplaces

Use: Optional

Data Type: Long

The number of places to include after the decimal point.

Return Value

The same data type as expression.

Description

Rounds a given number to a specified number of decimal places.

Rules at a Glance

  • numdecimalplaces can be any whole number between 0 and 16.
  • Round follows standard rules for rounding:

    • If the digit in the position to the right of numdecimalplaces is greater than 5, the digit in the numdecimalplaces position is incremented by one.
    • If the digit in the position to the right of numdecimalplaces is less than 5, the digits to the right of numdecimalplaces are dropped.
    • If the digit in the position to the right of numdecimalplaces is 5 and the digit in the numdecimalplaces position is odd, the digit in the numdecimalplaces position is incremented by one.
    • If the digit in the position to the right of numdecimalplaces is 5 and the digit in the numdecimalplaces position is even, the digits to the right of numdecimalplaces are dropped.

Programming Tips and Gotchas

If expression is a string representation of a numeric value, Round converts it to a numeric value before rounding. However, if expression isn't a string representation of a number, Round generates runtime error 13, "Type mismatch." The IsNumeric function insures that expression is a proper numeric representation before calling Round.

See Also

Fix Function, Int Function

RTrim Function  

Syntax

RTrim(stringexp)

stringexp

Use: Required

Data Type: String

A valid string expression.

Return Value

A String.

Description

Removes any trailing spaces from stringexp.

Rules at a Glance

If stringexp contains a Null, RTrim returns Null.

Programming Tips and Gotchas

Unless you need to keep leading spaces, you should use the Trim function, which is the equivalent of RTrim(LTrim(string)), thereby clearing both leading and trailing spaces in a single function call.

VB/VBA Differences

Because it does not support strong typing, VBScript does not support the VBA RTrim$ function, which returns a strongly typed string rather than a string variant.

See Also

LTrim Function, Trim Function

ScriptEngine Function  

Syntax

ScriptEngine( )

Return Value

A String.

Description

Indicates the scripting language currently in use.

Rules at a Glance

According to the documentation, the function returns the values shown in the following table:

Return value

Description

JScript

Microsoft JScript

VBA

Visual Basic for Applications

VBScript

VBScript

Programming Tips and Gotchas

The function is implemented in VBScript.dll, as well as in JScript.dll. However, it is not implemented in the VB Version 6 runtime libraries. Calls to this function from VBA code will generate an error rather than return the string "VBA".

VBA/VBScript Differences

This function is not supported in VBA.

See Also

ScriptEngineBuildVersion Function, ScriptEngineMajorVersion Function

ScriptEngineBuildVersion Function  

Syntax

ScriptEngineBuildVersion( )

Return Value

A Long.

Description

Returns the build number of the VBScript script engine.

Programming Tips and Gotchas

The function is also implemented in the JScript script engine.

VBA/VBScript Differences

This function is not supported in VBA.

ScriptEngineMajorVersion Function  

Syntax

ScriptEngineMajorVersion( )

Return Value

A Long.

Description

Indicates the major version (1, 2, etc.) of the scripting language currently in use.

Rules at a Glance

The following table lists the versions of VBScript through 5.0, as well as the year in which they were released and the products with which they were initially released:

Version

Year

Product

1.0

1996

Internet Explorer 3.0

2.0

1997

IIS 2.0

3.0

1998

Internet Explorer 4.0, IIS 4.0, WSH 1.0, Outlook 98

4.0

1998

Visual Studio 6.0

5.0

1999

Internet Explorer 5.0

5.5

2001

Internet Explorer 5.5

5.6

2002

Microsoft Visual Studio .NET

Programming Tips and Gotchas

  • The function is also implemented in the JScript script engine.
  • If your script requires some functionality available in a baseline version, ordinarily you want to make sure that the script is running on that version or a later version. For instance, if your script requires regular expression support, which became available only in VBScript Version 5, you would test for the version with a code fragment like:

    If ScriptingEngineMajorVersion >= 5 Then

    You do not want to test for equality, as in:

    If ScriptingEngineMajorVersion = 5 Then

    since that may leave your script unable to run on versions of VBScript later than Version 5.

VBA/VBScript Differences

This function is not supported in VBA.

See Also

ScriptEngineBuildVersion Function, ScriptEngineMinorVersion Function

ScriptEngineMinorVersion Function  

Syntax

ScriptEngineMinorVersion( )

Return Value

A Long.

Description

Indicates the minor version (the number to the right of the decimal point) of the scripting language engine currently in use.

Programming Tips and Gotchas

  • The function is also implemented in the JScript script engine.
  • If your script requires some functionality available in a baseline minor version, you ordinarily would want to make sure that the script is running on that version or a later version. Test for a minor version with a code fragment like:

    lMajor = ScriptingEngineMajorVersion
    lMinor = ScriptingEngineMinorVersion
    If (lMajor = 5 And lMinor >= 1) Or (lMajor > 5) Then

    You should not test for equality, and you should never test for a minor version alone, without considering the major version.

VBA/VBScript Differences

This function is not supported in VBA.

See Also

ScriptEngine Function, ScriptEngineBuildVersion Function, ScriptEngineMajorVersion Function

Second Function  

Syntax

Second(time)

time

Use: Required

Data Type: String, numeric, or date/time

Any valid expression that can represent a time value.

Return Value

An Integer in the range 0 to 59.

Description

Extracts the seconds from a given time expression.

Rules at a Glance

If the time expression time is Null, the Second function returns Null.

See Also

Hour Function, Minute Function

Select Case Statement  

Syntax

Select Case testexpression
 [Case expressionlist
 [statements-n]] ...
 [Case Else
 [elsestatements]]
End Select

testexpression

Use: Required

Data Type: Any

Any numeric or string expression whose value determines which block of code is executed.

expressionlist

Use: Required

Data Type: Any

Comma-delimited list of expressions to compare values with testexpression.

statements-n

Use: Optional

Program statements to execute if a match is found between any section of expressionlist and testexpression.

elsestatements

Use: Optional

Program statements to execute if a match between testexpression and any expressionlist can't be found.

Description

Allows for conditional execution of a block of code, typically out of three or more code blocks, based on some condition. Use the Select Case statement as an alternative to complex nested If...Then...Else statements.

Rules at a Glance

  • Any number of Case clauses can be included in the Select Case statement.
  • If a match between testexpression and any part of expressionlist is found, the program statements following the matched expressionlist are executed. When program execution encounters the next Case clause or the End Select clause, execution continues with the statement immediately following the End Select clause.
  • Both expressionlist and testexpression must be a valid expression that can consist of one or more of the following: a literal value, a variable, an arithmetic or comparison operator, or the value returned by an intrinsic or user-defined function.
  • If used, the Case Else clause must be the last Case clause. Program execution encounters the Case Else clauseand thereby executes, the elsestatementsonly if all other expressionlist comparisons fail.
  • Select Case statements can also be nested, resulting in a successful match between testexpression and expressionlist being another Select Case statement.

Example

The following example uses Select Case to read a variable populated by the user and determine the name of the user's operating system:

Dim varOS, varOSDesc

Select Case varOS
 Case 1
 varOSDesc = "Windows NT"
 Case 2
 varOSDesc = "Windows 98"
 Case 3
 varOSDesc = "Windows 95"
 Case 4
 varOSDesc = "Windows 3.11"
 Case 5
 varOSDesc = "Windows 2000"
 Case 6
 varOSDesc = "Windows ME"
 Case 7
 varOSDesc = "Windows XP"
 Case Else
 varOSDesc = "OS is unknown"
End Select

Programming Tips and Gotchas

  • The Select Case statement is the VBA/VBScript equivalent of the Switch construct found in C and C++.
  • The Case Else clause is optional. However, as with If...Then...Else statements, it's often good practice to provide a Case Else to catch the exceptional instance whenperhaps unexpectedlya match can't be found in any of the expressionlists you have provided.
  • If testexpression satisfies more than one expressionlist comparison, only the code in the first is executed.

VBA/VBScript Differences

VBA supports two variations of expressionlist that are not supported by VBScript. These are shown in the following table:

Not supported

Examples

To keyword

Case 10 To 20, 110 To 120

Is keyword

Case Is >= 100Case Is <= 10, Is >= 100

See Also

If...Then Statement

SetLocale Function  

Syntax

SetLocale(lcid)

lcid

Use: Optional

Data Type: Long or String

A number representing a locale ID.

Return Value

A Long indicating the previous locale ID.

Description

Sets the current locale ID.

Rules at a Glance

  • A locale ID represents language as well as regional conventions. It determines such things as keyboard layout, alphabetic sort order, and date, time, number, and currency formats.
  • Appendix D lists valid locale IDs.
  • If SetLocale is called with no arguments, it resets the script locale back to the host default, which is usually the user default.
  • If lcid is zero or 1024, the locale is set as defined by the user's locale ID.
  • If lcid is 2048, the local is set as defined by the system's regional settings.

Programming Tips and Gotchas

  • There is no need to call GetLocale and store its returned value before calling SetLocale, since SetLocale returns the value of the previous locale ID.
  • SetLocale sets the locale ID of the script engine only. It does not affect the system, user, or host/application locale IDs.

VBA/Script Differences

The SetLocale function is not supported by VBA.

See Also

GetLocale Function

Join Discussion Forum

 

Join the Discussion Forum

Name:
Email Address:
 

Following is the source for AddContact.asp, the ASP application that instantiates an instance of the CContact class to handle data access using ADO:


 

Our Discussion Forum

From the Discussion Forum...

<% Dim oContact Set oContact = New CContact Response.Write oContact.AddContact %>

Programming Tips and Gotchas

  • You can have more than one object variable referring to the same object. However, bear in mind that a change to the underlying object using one object variable is reflected in all the other object variables that reference that object. For example, consider the following code fragment, in which the objColorCopy object reference is set equal to the objColor object:

    Dim objColor, objColorCopy
    Set objColor = New CColor ' CColor class not shown
    Set objColorCopy = objColor
    
    objColor.CurrentColor = "Blue"
    Msgbox objColorCopy.CurrentColor

    Since both objColor and objColorCopy reference a single object, the value of the CurrentColor property is Blue in both cases.

  • It is commonly believed that you should release object references as soon as you are finished with them using code like the following:

    Dim myClass
    Set myClass = New SomeObject
    ' Do something here
    Set myClass = Nothing

    Most of the time, though, releasing object references is unnecessary, since they are released anyway by the garbage collector when the object reference goes out of scope. There are only a couple of situations in which it is necessary to explicitly release object references:

    1. When the object encapsulates a scarce resource, such as a database connection. In this case, it often makes sense to release the object reference as soon as you are done with it.
    2. When two objects hold references to one another. In this situation, the objects are not destroyed when their references go out of scope. And their references going out of scope means that it is no longer possible to release the objects programmatically. VBScript objects (i.e., objects instantiated from classes declared with the Class... End Class construct will be destroyed when the scripting engine is torn down, which may be before application shutdown. COM objects instantiated with the CreateObject or GetObject functions, though, may persist until the application terminates. Since terminating a web server or the ASP process, in particular, is highly undesirable, it is far preferable to release object references explicitly by setting them to nothing. The following code illustrates a circular reference:

       Class MyClass
       Dim Subclass
      
       Public Property Get MySubclass
       Set MySubclass = Subclass
       End Property
      
       Public Property Set MySubclass(value)
       Set Subclass = value
       End Property
       End Class
      
       Dim myClass1, myClass2
      
       Set myClass1 = New MyClass
       Set myClass2 = New MyClass
      
       Set myClass1.MySubclass = myClass2
       Set myClass2.MySubclass = myClass1
  • When trying to discover whether an object reference has been successfully assigned, you should determine if the object variable has been assigned as Nothing. However, you can't use the equality comparison operator (=) for this purpose; you must use the Is operator, as the following code snippet shows:

    If objectvar Is Nothing Then
     ... 'assignment failed
    End If
  • Any function that returns an object reference requires the use of the Set statement to assign the reference to a variable. This includes the VBScript CreateObject and GetObject functions, as well as the WSH WScript.CreateObject method and the ASP Server.CreateObject method.

    Dim oMainObject
    Set oMainObject = CreateObject("MainLib.MainObject")

VBA/VBScript Differences

  • An external createable object can be instantiated using VBA's New when the variable is declared if the VBA project has a reference to its type library:

    Dim oFS As New Scripting.FileSystemObject

    In this case, there is no need use the Set statement to instantiate the object, since it will be instantiated when it is next referenced in code. Since this early binding is not supported by VBScript, however, this use of the New keyword is not allowed.

  • An external createable object can be instantiated using the VBA New keyword along with the Set statement if the VBA project has a reference to its type library. For example:

    Dim oFS As Scripting.FileSystemObject
    Set oFS = New Scripting.FileSystemObject

    Since VBScript does not support early binding, however, this usage is not allowed. The Set statement, along with the New keyword, can be used only to instantiate a class declared with the Class...End Class construct.

See Also

CreateObject Function, GetObject Function, GetRef Function

Set Statement  

Syntax

Set objectvar = (objectexpression | New classname Nothing)

objectvar

Use: Required

Data Type: Object

The name of the object variable or property.

objectexpression

Use: Optional

Data Type: Object

An expression evaluating to an object.

New

Use: Optional

Type: Keyword

Creates a new instance of an object defined using the Class...End Class construct, or with the syntax New RegExp instantiates the Regular Expression object.

classname

Use: Required

Data Type: String literal

The name of the class defined by the Class...End Class construct to be instantiated.

Nothing

Use: Optional

Type: Keyword

Assigns the special data type Nothing to objectvar, thereby releasing the reference to the object.

Description

Assigns an object reference to a variable or property.

Rules at a Glance

  • objectvar doesn't hold a copy of the underlying object; it simply holds a reference to the object.
  • If the New keyword is used is used to instantiate a VBScript class defined using the Class...End Class construct, a new instance of the class is immediately created and its Class Initialize event fires. This applies only to classes defined using the Class...End Class construct.

    You can also instantiate a Regular Expression object with the New keyword by using a statement like the following:

     Set oRegExp = New RegExp
  • All classes defined by the Class...End Class construct can be created using the New keyword. For external objects, the application's object model determines which objects can be created and which cannot.
  • If objectvar holds a reference to an object when the Set statement is executed, the current reference is released and the new one referred to in objectexpression is assigned.
  • objectexpression can be any of the following:

    • The name of an object. This creates a duplicate object reference in which two references point to the same object. For instance:

       Dim oFS, oRoot, oFolder
       Set oFS = CreateObject("Scripting.FileSystemObject")
       Set oRoot = oFS.Drives("C").RootFolder
       Set oFolder = oRoot
    • A variable that has been previously declared and instantiated using the Set statement and that refers to the same type of object:

       Dim dSpace
       Dim oFS, oDrive
      
       dSpace = CDbl(0)
       Set oFS = CreateObject("Scripting.FileSystemObject")
       Set oDrive = oFS.Drives("C")
       dSpace = dSpace + oDrive.FreeSpace
       Set oDrive = oFS.Drives("D")
       dSpace = dSpace + oDrive.FreeSpace
      
       MsgBox "Total free space: " & dSpace & " " & typename(dSpace)
    • A call to a function, method, or property that returns the same type of object.
  • By assigning Nothing to objectvar, the reference held by objectvar to the object is released.

Example

The following code creates a simple web page that prompts the user for a name and an email address if she desires to be added to a discussion forum:


 
Sgn Function  

Syntax

Sgn(number)

number

Use: Required

Data Type: Any expression capable of conversion into a numeric value

A numeric expression.

Return Value

An Integer.

Description

Determines the sign of a number.

Rules at a Glance

The return value of the Sgn function is determined by the sign of number:

If number is...

Sgn returns

Positive

1

Zero

0

Negative

-1

Programming Tips and Gotchas

  • If you're planning on using the Sgn function to evaluate a result to False (0) or True (any nonzero value), you could also use the CBool function.
  • The major use for Sgna fairly trivial oneis to determine the sign of an expression. It's equivalent to the following code:

    Function Sgn(varNumber)
     If varNumber > 0 Then
     Sgn = 1
     ElseIf varNumber = 0 Then
     Sgn = 0
     Else
     Sgn = -1
     End If
    End Function
  • Sgn is useful in cases in which the sign of a quantity defines the sign of an expression. For example:

    lngResult = lngQty * Sgn(lngValue)
  • Although Sgn handles the conversion of strings to numeric data, it's a good idea to make sure that number is valid by calling the IsNumeric function before the call to Sgn.

See Also

If...Then Statement

Sin Function  

Syntax

Sin(number)

number

Use: Required

Data Type: Numeric

An angle expressed in radians.

Return Value

A Double containing the sine of an angle.

Description

Returns the ratio of two sides of a right triangle in the range -1 to 1.

Rules at a Glance

The ratio is determined by dividing the length of the side opposite the angle by the length of the hypotenuse.

Programming Tips and Gotchas

  • You can convert radians to degrees using the formula:

    radians = degrees * (pi/180) 
  • You can convert degrees to radians using the formula:

    degrees = radians * (180/pi)
Space Function  

Syntax

Space(number)

number

Use: Required

Data Type: Integer

An expression evaluating to the number of spaces required.

Return Value

A String containing number spaces.

Description

Creates a string containing number spaces.

Rules at a Glance

  • While number can be zero (in which case the function returns a empty string), runtime error 5, "Invalid procedure call or argument," is generated if number is negative.
  • Space is a "convenience function" that is equivalent to the function call:

    sString = String(number, 32)

VBA/VBScript Differences

VBScript doesn't support the VBA Space$ function.

Split Function  

Syntax

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

expression

Use: Required

Data Type: String

A string to be broken up into multiple strings.

delimiter

Use: Optional

Data Type: String

The character used to delimit the substrings in expression.

count

use: Optional

Data Type: Long

The number of strings to return.

compare

Use: Optional

Data Type: Long

The method of comparison. Possible values are vbBinaryCompare or vbTextCompare. Note that both are intrinsic VBScript constants; you do not have to define them yourself using the Const statement.

Return Value

A variant array consisting of the arguments passed into the function.

Description

Parses a single string containing delimited values into an array.

Rules at a Glance

  • If delimiter isn't found in expression, Split returns the entire string in element 0 of the return array.
  • If delimiteris omitted, a space character is used as the delimiter.
  • If count is omitted or its value is -1, all strings are returned.
  • The default comparison method is vbBinaryCompare. If delimiter is an alphabetic character, this setting controls whether the search for it in expression is case-sensitive (vbBinaryCompare) or not (vbTextCompare).
  • Once count has been reached, the remainder of the string is placed, unprocessed, into the next element of the returned array.

Programming Tips and Gotchas

  • The variable you declare to assign the return value of Filter must be a simple variant, rather than a variant array. The following code is incorrect:

    ' Incorrect
    Dim sArray( )
    sArray = Split(sString, ",")

    This error is corrected in the following code fragment:

    ' Correct
    Dim sArray
    sArray = Split(sString, ",")
  • Strings are written to the returned array in the order in which they appear in expression.

See Also

Join Function

Sqr Function  

Syntax

Sqr(number)

number

Use: Required

Data Type: Double

Any numeric expression greater than or equal to 0.

Return Value

A Double containing the square root of number.

Description

Calculates the square root of a given number.

Rules at a Glance

number must be equal to or greater than zero or runtime error 5, "Invalid procedure call or argument," occurs.

StrComp Function  

Syntax

StrComp(string1, string2[, compare])

string1

Use: Required

Data Type: String

Any string expression.

string2

Use: Required

Data Type: String

Any string expression.

compare

Use: Optional

Data Type: Integer constant

The type of string comparison to perform.

Return Value

An Integer.

Description

Determines whether two strings are equal and which of two strings is greater.

Rules at a Glance

  • The following intrinsic constants are available as the settings for compare:

Constant

Value

Comparison to perform

vbBinaryCompare

0

Binary (default)

vbTextCompare

1

Textual

  • If compare isn't specified, its value defaults to vbBinaryCompare. In other words, the comparison of string1 and string2 is case-sensitive.
  • This table describes the possible return values from the StrComp function:

Scenario

Return value

string1 < string2

-1

string1 = string2

0

string1 > string2

1

string1 or string2 is Null

Null

Programming Tips and Gotchas

  • If you just need to know whether string1 is greater than string2 (or vice versa), couldn't you simply use the < or > comparison operators? When you're dealing with strings of characters, VBScript sees each character as a number. Simply using the comparison operators therefore compares the numerical value of one string with the other. Take this scenario:

    Dim sString1
    Dim sString2
    
    sString1 = "hello world"
    sString2 = "HELLO WORLD"

    Subjectively, because of the significance of uppercase letters in text, we'd probably say that sString2 is greater than sString1. But VBScript sees these strings as a series of Unicode numbers, and because uppercase characters have a lower Unicode number than lowercase numbers, the lowercase string (sString1) is greater.

    This is similar to how the default StrComp option vbBinaryCompare operatescomparing the Unicode numbers of each string at binary level. The sort order is derived from the international binary representations of the characters. vbCompareText performs a case-insensitive search, which means that it ignores the difference between upper- and lowercase characters. It also means that it will equate different representations of the same character in some Far Eastern character sets. vbCompareText, in other words, indicates a case-insensitive textual sort order as determined by the user's locale.

  • Even performing a simple single comparison like:

    If UCase(sString1) < UCase(sString2) Then

    shows a performance hit of about 30 percent over the much more elegant and efficient StrComp function call:

    If StrComp(sString1,sString2, vbTextCompare) = -1
    Then

    The former version, though, is easier to read and makes the code self-documenting.

String Function  

Syntax

String(number, character)

number

Use: Required

Data Type: Long

The length of the required string.

character

Use: Required

Data Type: Variant

Character or character code used to create the required string.

Return Value

A string made up of character, repeated number times.

Description

Creates a string comprising a specified single character repeated a specified number of times.

Rules at a Glance

  • If number contains Null, Null is returned.
  • If character contains Null, Null is returned.
  • character can be specified as a string or as an ANSI character code. For example:

    strBuffer1 = String(128, "=") ' Fill with "="
    strBuffer2 = String(128, 0) ' Fill with Chr$(0)
  • If character consists of multiple characters, the first character is used only, and the remainders are discarded.

Programming Tips and Gotchas

  • The String function is useful for creating long strings of _, -, or = characters to create horizontal lines for delimiting sections of a report.

VB/VBA Differences

VBScript does not support the VBA String$ function.

See Also

Space Function

StrReverse Function  

Syntax

StrReverse(str_expression)

str_expression

Use: Required

Data Type: String

The string whose characters are to be reversed.

Return Value

A String.

Description

Returns a string that is the reverse of the string passed to it. For example, if the string "and" is passed to it as an argument, StrReverse returns the string "dna."

Rules at a Glance

  • If str_expression is a zero-length string (" "), the function's return value is a zero-length string.
  • If str_expression is Null, the function generates runtime error 94, "Invalid use of Null."
Sub Statement  

Syntax

[Public [Default] | Private] Sub name [(arglist)] 
 [statements]
 [Exit Sub] 
 [statements]
End Sub

Public

Use: Optional

Type: Keyword

Gives the sub procedure visibility to all scripts. If used in a class definition, the sub procedure is also accessible from outside the class. Public and Private are mutually exclusive.

Default

Use: Optional

Type: Keyword

Indicates that a public procedure defined in a VBScript class (that is, defined within a Class...End Class construct) is the default member of the class.

Private

Use: Optional

Type: Keyword

Restricts the visibility of the sub procedure to those procedures within the same script. In a class definition, restricts the visibility of the sub procedure to the class itself. Public and Private are mutually exclusive.

name

Use: Required

The name of the sub procedure.

arglist

Use: Optional

Data Type: Any

A comma-delimited list of variables to be passed to the sub procedure as arguments from the calling procedure.

statements

Use: Optional

Program code to be executed within the sub procedure.

arglist uses the following syntax and parts:

[ByVal | ByRef] varname[( )]

ByVal

Use: Optional

The argument is passed by value; that is, a local copy of the variable is assigned the value of the argument.

ByRef

Use: Optional

The argument is passed by reference; that is, the local variable is simply a reference to the argument being passed. All changes made to the local variable are also reflected in the calling argument. ByRef is the default method of passing variables.

varname

Use: Required

The name of the local variable containing the reference or argument value.

Description

Defines a sub procedure.

Rules at a Glance

  • If you don't include the Public or Private keywords, a sub procedure is Public by default.
  • Unlike a Function procedure, a sub procedure doesn't return a value to the calling procedure. You would think that this means that a sub procedure can't be used as part of an expression, but in fact this isn't the case; subs can be included in expressions are treated as functions that return Empty.
  • Any number of Exit Sub statements can be placed within the sub procedure. Execution continues with the line of code immediately following the call to the sub procedure.
  • Only one property, procedure, or function in a class can be designated as its default member by assigning it the Default keyword.
  • The Default keyword can be used only with public procedures.
  • You can invoke a sub procedure using the Call statement, in which parameters are enclosed in parentheses. For example:

     Call MySub(param1, param2)

    You can also omit the Call keyword, in which case the parentheses around parameters are also omitted. For example:

     MySub param1, param2

Programming Tips and Gotchas

  • There is often confusion between the ByRef and ByVal methods of assigning arguments to the sub procedure. ByRef assigns the reference of the variable in the calling procedure to the variable in the sub procedure. As a result, any changes made to the variable from within the sub procedure are, in reality, made to the variable in the calling procedure. On the other hand, ByVal assigns the value of the variable in the calling procedure to the variable in the sub procedure; that is, it makes a separate copy of the variable in a separate memory location. Changes made to the variable in the sub procedure have no effect on the variable in the calling procedure.
  • You can override arguments passed to sub procedures by reference and instead pass them by value by enclosing them in parentheses. For instance, in the code:

     Dim x
     x = 10
     SubByRef(x)
     MsgBox "x after SubByRef: " & x
    
     Sub SubByRef(y)
     y = 20
     End Sub

    x retains its original value of 10 when control returns from the SubByRef sub procedure. Note that you can enclose the argument list in parentheses when there is a single argument, but that argument is then passed to the calling sub procedure by value rather than by reference.

    If a sub procedure has two or more arguments, you can pass a particular argument by reference by enclosing it in parentheses. For instance:

     Dim x, x1
     x = 10
     x1 = 10
     SubByRef (x),x1 ' after return, x=10, x1=20
     x1 = 10
     Call SubByRef((x), x1) ' after return, x=10, x1=20
     Sub SubByRef(y, z)
     y = 20
     z = 20
     End Sub
  • Sub procedures can't return a value, or can they? Look at the following code:

    Sub testTheReturns( )
     Dim iValOne
     
     iValOne = 10
     testValues iValOne
     Msgbox iValOne
    End Sub
    
    Sub testValues(ByRefiVal) 
     iVal = iVal + 5
    End Sub

    Because the argument was passed with ByRef, the sub procedure acted upon the underlying variable iValOne. This means that you can use ByRef to obtain a "return" value or values (although they're not strictly return values) from a sub procedure call.

  • There are many occasions in which recursively calling a sub procedure can be used to solve a programming problem. Recursion occurs when you call a sub procedure from within itself. Recursion is a legitimate and often essential part of software development; for example, it offers a reliable method of enumerating or iterating a hierarchical structure. However, you must be aware that recursion can lead to stack overflow. The extent to which you can get away with recursion really depends upon the complexity of the sub procedure concerned, the amount and type of data being passed in, and an infinite number of other variables and unknowns.

See Also

Call Statement, Exit Statement, Function Statement

Tan Function  

Syntax

Tan (number)

number

Use: Required

Data Type: Numeric expression

An angle in radians.

Return Value

A Double containing the tangent of an angle.

Description

Returns the ratio of two sides of a right-angle triangle.

Rules at a Glance

The returned ratio is derived by dividing the length of the side opposite the angle by the length of the side adjacent to the angle.

Programming Tips and Gotchas

  • You can convert degrees to radians using the following formula:

    radians = degrees * (pi/180) 
  • You can convert radians to degrees using the following formula:

    degrees = radians * (180/pi)
Terminate Event  

Syntax

Private Sub Class_Terminate( )

Description

The Terminate event is fired when an instance of a class is removable from memory.

Rules at a Glance

  • The Terminate event applies to classes defined with the Class...End Class construct.
  • Instances of a class are removed from memory by explicitly setting the object variable to Nothing or by the object variable going out of scope.
  • If a script ends because of a runtime error, a class's Terminate event isn't fired.

Example

The following example shows a typical Terminate event in a class object that decrements a global instance counter used to ensure that only a single instance of a particular utility object is created. When the counter reaches 0, the global object reference to the utility object is destroyed.

Private Sub Class_Terminate( )

 glbUtilCount = glbUtilCount - 1
 If glbUtilCount = 0 then
 Set goUtils = Nothing
 End If
 
End Sub

Programming Tips and Gotchas

  • Because the Terminate event is fired when an object becomes removable from memory, it is possible, but not recommended, for the Terminate event handler to add references back to itself and thereby prevent its removal. However, in this case, when the object actually is released, the Terminate event handler will not be called again.
  • The Terminate event is fired under the following conditions:

    • An object goes out of scope.
    • The last reference to an object is set equal to Nothing.
    • An object variable is assigned a new object reference.
  • The Terminate event is fired when an object is about to be removed from memory, not when an object reference is about to be removed. In other words, if two variables reference the same object, the Terminate event will be fired only once, when the second reference is about to be destroyed.

See Also

Initialize Event, Set Statement

TextStream Object  

Createable

No

Returned by

File.OpenTextStream Method

FileSystemObject.CreateTextFile Method

FileSystemObject.GetStandardStream Method

FileSystemObject.OpenTextFile Method

Library

Microsoft Scripting Runtime

Windows Script Host

Description

Most commonly, the TextStream object represents a text file. As of Windows Script Host 2.0 and VBScript 5.5, however, it also represents any input/output stream, such as standard input, standard output, and the standard error stream. Depending on the precise character of the I/O stream, you can open a TextStream object to read from, append to, or write to the stream. The TextStream object provides methods to read, write, and close the text file or I/O stream.

When dealing with files, note that the TextStream object represents the file's contents or internals; the File object represents the file's externals or the file as an object in the filesystem.

The TextStream object is one of the objects in the File System object model; for an overview of the model, including the library reference needed to access it, see the File System Object Model entry.

Properties

The availability of TextStream object properties depends on the precise character of the TextStream object; some properties are available only when the stream is opened in read mode (indicated by an R in the Availability field); others are available in both read and write modes (indicated by a RW in the Availability field). All of the following TextStream object properties are read-only:

AtEndOfLine

Data Type: Boolean

Availability: R

A flag denoting whether the end-of-a-line marker has been reached (True) or not (False). Relevant only when reading a file.

When reading a standard input stream from the keyboard, the end of a line is indicated by pressing the Enter key.

AtEndofStream

Data Type: Boolean

Availability: R

A flag denoting whether the end of the stream has been reached (True) or not (False). Relevant only when reading a file.

When reading from a standard input stream from the keyboard, the end of the input stream is indicated by the Ctrl-Z character.

Column

Data Type: Long

Availability: RW

Returns the column number position of the file marker. The first column position in the input stream and in each row is 1.

Examining the value of the Column property is most useful in input streams after calls to the TextStream object's Read and Skip methods. Although it is less useful for output streams, it can be used after a call to the TextStream object's Write method.

Line

Data Type: Long

Availability: RW

Returns the line number position of the file marker. Lines in the text stream are numbered starting at 1.

Unless the end of the text stream has been reached, the value of the Line property is incremented after calls to the ReadAll, ReadLine, and SkipLine methods. Similarly, in output streams, it is incremented after calls to the WriteLine and WriteBlankLines methods.

Methods

Close

Read

ReadAll

ReadLine

Skip

SkipLine

Write

WriteBlankLines

WriteLine

TextStream.Close Method  

Syntax

oTextStreamObj.Close 

Availability

RW

Description

Closes the current TextStream object.

Rules at a Glance

Although calling the Close method does not invalidate the object reference, you shouldn't try to reference a TextStream object that has been closed.

Programming Tips and Gotchas

  • After closing the TextStream object, set oTextStreamObj to Nothing.
  • If you are writing to a file-based text stream, text is automatically written to the file. You do not have to call the Save method to commit changes to a disk file before calling the Close method.
TextStream.Read Method  

Syntax

oTextStreamObj.Read(Characters)

oTextStreamObj

Use: Required

Data Type: TextStream object

Any property or object variable returning a readable TextStream object.

Characters

Use: Required

Data Type: Long

The number of characters you want to read from the input stream.

Return Value

A String.

Availability

R

Description

Reads a given number of characters from a file or the standard input and returns the resulting string.

Rules at a Glance

  • Files opened for writing or appending can't be read; you must first close the file and reopen it using the ForReading constant.
  • After the read operation, the file pointer advances Characters characters, unless the end of the file is encountered.
  • If the number of characters available to be read are less than Characters, all characters will be read.
  • When reading the standard input stream from the keyboard, program execution pauses until an end-of-line or end-of-stream character is encountered. However, only the first Characters characters of the stream are read. If at least Characters characters are available in the input stream for subsequent read operations, program execution does not pause to wait for further keyboard input. The usual technique is to process keystrokes in a loop until the end-of-stream marker is encountered. For example:

    Do While Not oIn.AtEndOfStream
     sIn = oIn.Read(10) ' Read up to 10 characters
     ' process text
    Loop

See Also

TextStream.ReadAll Method , TextStream.ReadLine Method

TextStream.ReadAll Method  

Syntax

oTextStreamObj.ReadAll

Return Value

A String.

Availability

R

Description

Reads the entire file or input stream into memory.

Rules at a Glance

  • For large files, use the ReadLine or Read methods to reduce the load on memory resources.
  • Files opened for writing or appending can't be read; you must first close the file and reopen it using the ForReading constant.
  • When used to read the standard input stream from the keyboard, the ReadAll method pauses program execution and polls the keyboard until the AtEndOfStream symbol is encountered. For this reason, the ReadAll method should not be executed repeatedly in a loop.

See Also

TextStream.Read Method , TextStream.ReadLine Method

TextStream.ReadLine Method  

Syntax

oTextStreamObj.ReadLine

Return Value

A String.

Availability

R

Description

Reads a line of the text file or input stream into memory, from the start of the current line up to the character immediately preceding the next end-of-line marker.

Rules at a Glance

  • Files opened for writing or appending can't be read; you must first close the file and reopen it using the ForRead constant.
  • The ReadLine method causes the file pointer to advance to the beginning of the next line, if there is one.
  • When used to retrieve standard input from the keyboard, the ReadLine method pauses program execution and waits until the end-of-line character (i.e., the Enter key) has been pressed. Unless your script expects to retrieve just one line of input, it's best to call the ReadLine method repeatedly in a loop.

See Also

TextStream.Read Method , TextStream.ReadAll Method

TextStream.Skip Method  

Syntax

oTextStreamObj.Skip (Characters)

oTextStreamObj

Use: Required

Data Type: TextStream object

Any property or object variable returning a readable TextStream object.

NoOfChars

Use: Required

Data Type: Long

Number of characters to skip when reading.

Availability

R

Description

Ignores the next Characters characters when reading from a text file or input stream.

Rules at a Glance

  • As a result of the skip operation, the file pointer is placed at the character immediately following the last skipped character.
  • The Skip method is available only for input streamsthat is, for files or streams opened in ForReading mode.

See Also

TextStream.SkipLine Method

TextStream.SkipLine Method  

Syntax

oTextStreamObj.SkipLine 

Availability

R

Description

Ignores the current line when reading from a text file.

Rules at a Glance

  • The SkipLine method is available only for files opened in ForReading mode.
  • After the SkipLine method executes, the internal file pointer is placed at the beginning of the line immediately following the skipped line, assuming that one exists.
TextStream.Write Method  

Syntax

oTextStreamObj.Write(Text) 

oTextStreamObj

Use: Required

Data Type: TextStream object

Any property or object variable returning a writable TextStream object.

Text

Use: Required

Data Type: String

Any string expression to write to the file.

Availability

W

Description

Writes a string to the text file.

Rules at a Glance

The file marker is set at the end of string. As a result, subsequent writes to the file adjoin each other, with no spaces inserted. To write data to the file in a more structured manner, use the WriteLine method.

See Also

TextStream.WriteBlankLines Method , TextStream.WriteLine Method

TextStream.WriteBlankLines Method  

Syntax

oTextStreamObj.WriteBlankLines(Lines)

oTextStreamObj

Use: Required

Data Type: TextStream object

Any property or object variable returning a writable TextStream object.

Lines

Use: Required

Data Type: Long

The number of newline characters to insert.

Availability

W

Description

Inserts one or more newline characters in the file or output stream at the current file marker position.

See Also

TextStream.Write Method , TextStream.WriteLine Method

TextStream.WriteLine Method  

Syntax

oTextStreamObj.WriteLine (String)

oTextStreamObj

Use: Required

Data Type: TextStream object

Any property or object variable returning a writable TextStream object.

String

Use: Required

Data Type: String

A string expression to write to the file.

Availability

W

Description

Writes a string immediately followed by a newline character to a text file.

See Also

TextStream.WriteBlankLines Method

Time Function  

Syntax

Time

Return Value

A Date.

Description

Returns the current system time.

Rules at a Glance

The Time function returns the time.

Programming Tips and Gotchas

The Time function returns but does not allow you to set the system time.

VBA/VBScript Differences

VBA includes a Time$ function that returns the time as a string rather than a variant. Because VBScript does not support strong typing, the function is not implemented in VBScript.

See Also

Now Function

Timer Function  

Syntax

Timer( )

Return Value

A Single.

Description

Returns the number of seconds since midnight.

Programming Tips and Gotchas

  • You can use the Timer function as an easy method of passing a seed number to the Randomize statement, as follows:

    Randomize Timer
  • The Timer function is ideal for measuring the time taken to execute a procedure or program statement, as the following ASP snippet shows:

    <%
    Dim sStartTime
    Dim i, j
    
    sStartTime = Timer()
    For i = 1 To 100
     Response.Write "Hello 
    "
     For j = 0 To 1000
     Next
    Next
    Response.Write "Time Taken = " & _
     FormatDateTime(Timer - sStartTime, vbShortTime) & _
     " Seconds"
    %>
TimeSerial Function  

Syntax

TimeSerial(hour, minute, second)

hour

Use: Required

Data Type: Integer

A number in the range 0 to 23.

minute

Use: Required

Data Type: Integer

Any valid integer.

second

Use: Required

Data Type: Integer

Any valid integer.

Return Value

A Date.

Description

Constructs a valid time given a number of hours, minutes, and seconds.

Rules at a Glance

  • Any of the arguments can be specified as relative values or expressions.
  • The hour argument requires a 24-hour clock format; however, the return value is always in a 12-hour clock format suffixed with A.M. or P.M.
  • If any of the values are greater than the normal range for the time unit to which it relates, the next higher time unit is increased accordingly. For example, a second argument of 125 is evaluated as 2 minutes 5 seconds.
  • If any of the values are less than zero, the next higher time unit is decreased accordingly. For example, TimeSerial(2,-1,30) returns 01:59:30.
  • If any of the values are outside the range -32,768 to 32,767, an error occurs.
  • If the value of any parameter causes the date returned by the function to fall outside the range of valid dates, an error occurs.

Programming Tips and Gotchas

Because TimeSerial handles time units outside of their normal limits, it can be used for time calculations. However, because the DateAdd function is more flexible and is internationally aware, it should be used instead.

See Also

DateAdd Function

TimeValue Function  

Syntax

TimeValue(time)

time

Use: Required

Data Type: String

Any valid string representation of a time.

Return Value

A Date.

Description

Converts a string representation of a time to a Variant Date type.

Rules at a Glance

  • If time is invalid, a runtime error is generated.
  • If time is Null, TimeValue returns Null.
  • Both 12- and 24-hour clock formats are valid.
  • Any date information contained within time is ignored by the TimeValue function.
  • If TimeValue returns invalid time information, an error occurs.

Programming Tips and Gotchas

  • A time literal can also be assigned to a Variant or Date variable by surrounding the date with hash characters (#), as the following snippet demonstrates:

    Dim dMyTime
    dMyTime = #12:30:00 AM#
  • The CDate function can also cast a time expression contained within a string as a Date variable, with the additional advantage of being internationally aware.

See Also

CDate Function, TimeSerial Function

Trim Function  

Syntax

Trim(string)

string

Use: Required

Data Type: String

Any string expression.

Return Value

A String.

Description

Returns a string in which any leading and trailing spaces in an original string are removed.

Rules at a Glance

If string is Null, the Trim function returns Null.

Programming Tips and Gotchas

Trim combines into a single function call what would otherwise be separate calls to the RTrim and LTrim functions.

VBA/VBScript Differences

VBA includes a Trim$ function that returns the a trimmed string rather than a trimmed string variant. Because VBScript does not support strong typing, the function is not implemented in VBScript.

See Also

LTrim Function, RTrim Function

TypeName Function  

Syntax

TypeName(varname)

varname

Use: Required

Data Type: Any

The name of a variable.

Return Value

A String.

Description

Returns a string containing the name of the data type of a variable.

Rules at a Glance

  • TypeName returns the variant's data type. If the variant has not been assigned a value, TypeName returns Empty. Therefore, TypeName never actually returns the string "Variant."
  • The following table describes the possible return values and their meaning:

Return value

Underlying data type

Boolean

Boolean

Byte

Byte

classname

An object variable of type classname

Currency

Currency

Date

Date

Decimal

Decimal

Double

Double-precision floating-point number

Empty

Uninitialized variable

Error

A missing argument error

Integer

Integer

Long

Long integer

Nothing

A variable of type Object that is not set to a valid object

Null

No valid data

Object

A generic object

Single

Single-precision floating-point number

String

String

Unknown

An object whose type is unknown

Variant( )

An array

VBA/VBScript Differences

  • In VBA, the data type of a strongly typed variable can be ascertained earlier than the data type of a VBScript variable. For instance, in VBA, the code fragment:

    Dim lNumber As Long
    MsgBox TypeName(lNumber)

    indicates that lNumber is a long. The equivalent VBScript code fragment:

    Dim lNumber
    MsgBox TypeName(lNumber)

    indicates that lNumber is Empty, since it hasn't yet been assigned a value and therefore VBScript cannot determine its data type. (Note that, in VBA, if lNumber is defined as a variant, the behavior of the TypeName function is identical to its behavior in VBScript.)

  • In VBA, the type name of an object variable that has been declared but not yet initialized returns "Nothing." In VBScript, the TypeName function returns "Nothing" only for object variables that have been explicitly set equal to Nothing.
  • In VBScript, all arrays return the value Variant( ). In VBA, the return value depends on whether the array is strongly typed.
  • In part because VBA can be strongly typed, a number of data types are more common than their corresponding VBScript data types. The Decimal data type does not exist in VBScript, since VBScript does not support the CDec function, which is the only method available for defining a Decimal. Similarly, the Byte and Currency data types are much rarer in VBScript than in VBA.

See Also

VarType Function

UBound Function  

Syntax

UBound(arrayname[, dimension])

arrayname

Use: Required

An array variable or an expression that evaluates to an array.

dimension

Use: Optional

Data Type: Long

A number specifying the dimension of the array.

Return Value

A Long.

Description

Indicates the upper limit of a specified dimension of an array. The upper boundary is the largest subscript you can access within the specified array.

Rules at a Glance

  • If dimension isn't specified, 1 is assumed. To determine the upper limit of the first dimension of an array created by VBScript code, set dimension to 1, set it to 2 for the second dimension, and so on.
  • The upper bound of an array dimension can be set to any integer value using Dim, Private, Public, and Redim.

Programming Tips and Gotchas

  • Note that UBound returns the actual subscript of the upper bound of a particular array dimension.
  • UBound is especially useful for determining the current upper boundary of a dynamic array.
  • The UBound function works only with conventional arrays. To determine the upper bound of a collection object, retrieve the value of its Count or Length property.

See Also

LBound Function

UCase Function  

Syntax

UCase(string)

string

Use: Required

Data Type: String

A valid string expression.

Return Value

A String.

Description

Converts a string to uppercase.

Rules at a Glance

  • UCase affects only lowercase alphabetical letters; all other characters within string remain unaffected.
  • UCase returns Null if string contains a Null.

VBA/VBScript Differences

VBA includes a UCase$ function that returns an uppercase string rather than a uppercase string variant. Because VBScript does not support strong typing, the function is not implemented in VBScript.

See Also

LCase Function

Unescape function  

Syntax

Unescape(string)
string

Use: Required

Data Type: String

An encoded string

Return Value

A string variant containing the decoded version of string.

Description

Decodes a URL-encoded or HTML-encoded string.

Rules at a Glance

Replaces all encoded characters with their corresponding characters. Encoded values in the form of %xx are replaced with their corresponding ASCII characters, while values in the form %uxxxx are replaced with their corresponding Unicode characters.

Programming Notes

  • The Unescape function is not documented in the VBScript documentation.
  • The function corresponds to the JScript Unescape method.
  • If string has no encoded characters, the function merely returns string unchanged.
  • All encoded characters in the form %xx are replaced with their equivalent ASCII strings.
  • All encoded characters in the form %uxxxx are replaced with their equivalent Unicode character strings.

VB/VBA Differences

This function is not supported in VBA.

See Also

Escape Function

VarType Function  

Syntax

VarType(varname)

varname

Use: Required

The name of a variable.

Return Value

An Integer representing the data type of varname.

Description

Determines the data type of a specified variable.

Rules at a Glance

  • The following intrinsic constants can test the return value of the VarType function:

Constant

Value

Data type

vbBoolean

11

Boolean

vbByte

17

Byte

vbCurrency

6

Currency

vbDataObject

13

A data access object variable

vbDate

7

Date

vbDecimal

14

Decimal

vbDouble

5

Double-precision floating-point number

vbEmpty

0

Uninitialized

vbError

10

An error type that indicates a missing argument

vbInteger

2

Integer

vbLong

3

Long integer

vbNull

1

No valid data

vbObject

9

A generic object

vbSingle

4

Single-precision floating-point number

vbString

8

String

vbVariant

12

Variantreturned only with vbArray (8194)

  • If varname is an array created by VBScript code, the VarType function returns 8200 (vbArray) and vbVariant.
  • If varname is an array returned to the script by a component, the VarType function returns 8200 (vbArray) and the value representing the data type of the array. For instance, a Visual Basic Integer array returned to a VBScript script produces a value of 8196(vbInteger + vbArray).
  • To test for an array, you can use the intrinsic constant vbArray. For example:

    If VarType(myVar) And vbArray Then
     MsgBox "This is an array"
    End If

    Alternatively, you can also use the IsArray function.

Programming Tips and Gotchas

  • When you use VarType with an object variable, you may get what appears to be an incorrect return value. The reason for this is that if the object has a default property, VarType returns the data type of the default property.
  • There is no such value as vbNothing.
  • For most purposes, the TypeName function, which returns a string indicating a variable's data type, is much more convenient and easy to use.

VBA/VBScript Differences

  • In VBA, the data type of a strongly typed variable can be ascertained earlier than the data type of a VBScript variable. For instance, in VBA, the code fragment:

    Dim lNumber As Long
    MsgBox VarType(lNumber)

    returns vbLong, indicating that lNumber is a Long. The equivalent VBScript code fragment:

    Dim lNumber
    MsgBox VarType(lNumber)

    returns vbEmpty, indicating that lNumber is Empty, since it hasn't yet been assigned a value and therefore VBScript cannot determine its data type. (Note that, in VBA, if lNumber is defined as a variant, the behavior of the VarType function is identical to its behavior in VBScript.)

  • In VBA, if varname is an array, the value returned by the function is 8194 (vbArray) plus the value of the data type of the array. For example, an array of strings will return 8192 + 8 = 8200, or vbArray + vbString. In VBScript, all arrays return 8192 + 10, or vbArray + vbVariant.
  • In part because VBA can be strongly typed, a number of data types are more common than their corresponding VBScript data types. The Decimal data type does not exist in VBScript, since VBScript does not support the CDec function, which is the only method available for defining a Decimal. Similarly, the Byte and Currency data types are much rarer in VBScript than in VBA.

See Also

TypeName Function

Weekday Function  

Syntax

Weekday(date, [firstdayofweek])

date

Use: Required

Data Type: Variant

Any valid date expression.

firstdayofweek

Use: Optional

Data Type: Integer

Integer specifying the first day of the week.

Return Value

An Integer.

Description

Determines the day of the week of a given date.

Rules at a Glance

  • The following intrinsic VBScript constants determine the value returned by the Weekday function:

Constant

Return value

Day represented

vbSunday

1

Sunday

vbMonday

2

Monday

vbTuesday

3

Tuesday

vbWednesday

4

Wednesday

vbThursday

5

Thursday

vbFriday

6

Friday

vbSaturday

7

Saturday

  • If date is Null, the Weekday function also returns Null.
  • The following table describes the settings for the firstdayofweek argument:

Constant

Value

Description

vbUseSystem

0

Use the NLS API setting

vbSunday

1

Sunday (default)

vbMonday

2

Monday

vbTuesday

3

Tuesday

vbWednesday

4

Wednesday

vbThursday

5

Thursday

vbFriday

6

Friday

vbSaturday

7

Saturday

Programming Tips and Gotchas

  • If you specify a firstdayofweek argument, the function returns the day of the week relative to firstdayofweek. For instance, if you set the value of firstdayofweek to vbMonday (2), indicating that Monday is the first day of the week, and attempt to determine the day of the week on which October 1, 1996, falls, the function returns a 2. That's because October 1, 1996, is a Tuesday, the second day of a week whose first day is Monday.
  • Because the function's return value is relative to firstdayofweek, using the day of the week constants to interpret the function's return value is confusing, to say the least. If we use our October 1, 1996, example once again, the following expression evaluates to True if the day of the week is Tuesday:

    If vbMonday = WeekDay(CDate("10/1/96"), vbMonday) Then

See Also

DatePart Function, Day Function, Month Function, Year Function

WeekdayName Function  

Syntax

WeekdayName(WeekdayNo, [abbreviate [, FirstDayOfWeek]])

WeekdayNo

Use: Required

Data Type: Long

The ordinal number of the required weekday, from 1 to 7.

abbreviate

Use: Optional

Data Type: Boolean

Specifies whether to return the full day name or an abbreviation.

FirstDayOfWeek

Use: Optional

Data Type: Integer

Specifies which day of the week should be first.

Return Value

A String.

Description

Returns the real name of the day.

Rules at a Glance

  • WeekDayNo must be a number between 1 and 7, or the function generates runtime error 5, "Invalid procedure call or argument."
  • If FirstDayOfWeek is omitted, WeekdayName treats Sunday as the first day of the week.
  • The default value of abbreviate is False.

Programming Tips and Gotchas

  • You'd expect that, given a date, WeekDayName would return the name of that date's day. But this isn't how the function works. To determine the name of the day of a particular date, combine WeekDayName with a call to the WeekDay function, as the following code fragment shows:

    sDay = WeekDayName(Weekday(dDate, iFirstDay), _
     bFullName, iFirstDay)

    Note that the value of the FirstDayOfWeek argument must be the same in the calls to both functions for WeekDayName to return an accurate result.

See Also

Weekday Function

While . . . Wend Statement  

Syntax

While condition
 [statements]
Wend

condition

Use: Required

Data Type: Boolean

An expression evaluating to True or False.

statements

Use: Optional

Program statements to execute while condition remains True.

Description

Repeatedly executes program code while a given condition remains True.

Rules at a Glance

  • A Null condition is evaluated as False.
  • If condition evaluates to True, the program code between the While and Wend statements is executed. After the Wend statement is executed, control is passed back up to the While statement, where condition is evaluated again. When condition evaluates to False, program execution skips to the first statement following the Wend statement.
  • You can nest While...Wend loops within each other.

Programming Tips and Gotchas

The While...Wend statement remains in VBScript for backward compatibility only. It has been superseded by the much more flexible Do...Loop statement.

See Also

Do . . . Loop Statement

With Statement  

Syntax

With object
 [statements]
End With

object

Use: Required

Data Type: Object

A previously declared object variable.

statements

Use: Optional

Program code to execute against object.

Description

Performs a set of property assignments and executes other code against a particular object, thus allowing you to refer to the object only once. Because the object is referred to only once, the "behind the scenes" qualification of that object is also performed only once, leading to improved performance of the code block.

Rules at a Glance

  • The single object referred to in the With statement remains the same throughout the code contained within the With...End With block. Therefore, only properties and methods of object can be used within the code block without explicitly referencing the object. All other object references within the With...End statement must start with a fully qualified object reference.
  • With statements can be nested, as long as the inner With statement refers to a child object or a dependent object of the outer With statement.

See Also

Do . . . Loop Statement, Set Statement

Year Function  

Syntax

Year(date)

date

Use: Required

Data Type: Date

Any valid date expression.

Return Value

An Integer.

Description

Returns an integer representing the year in a given date expression.

Rules at a Glance

If date contains Null, Year returns Null.

Programming Tips and Gotchas

  • The validity of the date expression and position of the year element within the given date expression are initially determined by the locale settings of the Windows system. However, some extra intelligence relating to two-digit year values has been built into the Year function that surpasses the usual comparison of a date expression to the current locale settings.
  • What happens when you pass a date over to the Year function containing a two-digit year? Quite simply, when the Year function sees a two-digit year, it assumes that all values equal to or greater than 30 are in the 20th Century (i.e., 30 = 1930, 98 = 1998) and that all values less than 30 are in the 21st century (i.e., 29 = 2029, 5 = 2005). Of course, if you don't want sleepless nights rewriting your programs in the year 2029, you should insist on a four-digit year, which will see your code work perfectly for about the next 8,000 years!

See Also

DatePart Function, Day Function, IsDate Function, Month Function, Weekday Function

Part I: The Basics

Introduction

Program Structure

Data Types and Variables

Error Handling and Debugging

VBScript with Active Server Pages

Programming Outlook Forms

Windows Script Host 5.6

VBScript with Internet Explorer

Windows Script Components

Part II: Reference

Part III: Appendixes

Appendix A. Language Elements by Category

Appendix B. VBScript Constants

Appendix C. Operators

Appendix E. The Script Encoder



Vbscript in a Nutshell
VBScript in a Nutshell, 2nd Edition
ISBN: 0596004885
EAN: 2147483647
Year: 2003
Pages: 335

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