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.
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
See Also IsNumeric 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
Example <% Dim myArray myArray = Array(100, 2202, 3.3, 605, 512) Response.Write myArray(2) %> Programming Tips and Gotchas
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 |
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
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
See Also Chr, ChrB, ChrW Functions |
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
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
See Also Tan Function |
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
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
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. |
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
See Also IsNumeric 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
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
See Also IsNumeric 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
Example If IsNumeric(sMyNumber) Then curMyNumber = CCur(sMyNumber) End If Programming Tips and Gotchas
See Also FormatCurrency, FormatNumber, FormatPercent Functions |
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 :
Rules at a Glance
Programming Tips and Gotchas
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 |
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
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 |
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
Programming Tips and Gotchas
sSQL = "SELECT * from myTable where myColumn = " & Chr(34) & _ sValue & Chr(34)
See Also Asc, AscB, AscW Functions, CStr Function |
Programming Tips and Gotchas
See Also
CLng Function, Fix Function, FormatCurrency, FormatNumber, FormatPercent Functions, Int Function, IsNumeric 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
Example |
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
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
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
See Also
CInt Function, Fix Function, FormatCurrency, FormatNumber, FormatPercent Functions, Int Function, IsNumeric 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
Example |
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
Example Private Const my_Constant = 3.1417 Programming Tips and Gotchas
VBA/VBScript Differences
See Also Private Statement, Public Statement |
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
See Also Atn Function, Sin Function, Tan 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
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
VBA/VBScript Differences
See Also GetObject Function, Set Statement |
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
Example Dim sngMyNumber If IsNumeric(sMyNumber) then sngMyNumber = CSng(sMyNumber) End If Programming Tips and Gotchas
See Also FormatCurrency, FormatNumber, FormatPercent Functions, IsNumeric 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
|
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 |
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
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
Example Dim lNoOfIntervals lNoOfIntervals = 100 Msgbox DateAdd("d", lNoOfIntervals, Now) Programming Tips and Gotchas
See Also DateDiff Function, DatePart Function, DateSerial Function, IsDate 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
First Day of Week Constants
First Week of Year Constants
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
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
See Also DateAdd Function, DatePart Function, IsDate 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
First Day of Week Constants
First Week of Year Constants
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
Example Dim sTimeInterval Dim dtNow sTimeInterval = "n" 'minutes dtNow = Now MsgBox DatePart(sTimeInterval, dtNow) Programming Tips and Gotchas
See Also DateSerial Function, Day Function, Month Function, Year Function, Minute Function, Hour Function, Second 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
Example Dim iYear, iMonth, iday iYear = 1987 iMonth = 3 + 11 iday = 16 MsgBox DateSerial(iYear, iMonth, iday) Programming Tips and Gotchas
See Also DateAdd 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
Example Dim dateExpression dateExpression = #10 March 2003# If IsDate (dateExpression) Then MsgBox DateValue(dateExpression) Else MsgBox "Invalid date" End If Programming Tips and Gotchas
See Also CDate Function, DateSerial Function, IsDate 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
Programming Tips and Gotchas
See Also DatePart Function, Weekday Function, WeekdayName Function, Month Function, Year Function |
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:
Dictionary Object Methods The Dictionary object supports the following five methods:
|
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
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
See Also Dictionary.Key Property |
Data Type Long Description Sets or returns the mode used to compare the keys in a Dictionary object. Rules at a Glance
Programming Tips and Gotchas
|
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 |
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
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 %>
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
Programming Tips and Gotchas
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: |
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
See Also Dictionary.Keys Method |
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
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
|
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 |
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. |
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. |
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
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
VBA/VBScript Differences
See Also Const Statement, Private Statement, Public Statement, ReDim 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
Programming Tips and Gotchas
See Also For Each . . . Next Statement, For . . . Next Statement, While . . . Wend Statement |
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.
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. |
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 |
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:
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:
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 |
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
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 |
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
Methods
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
See Also Err.Clear Method, Err.Raise Method, On Error Statement |
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
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
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
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
Data Type String Description A read/write property containing a short string describing a runtime error. Rules at a Glance
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: |
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
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
VBA/VBScript Differences
See Also MsgBox Function, Err.HelpFile Property, Chapter 4 |
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
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 |
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
|
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
Programming Tips and Gotchas
See Also Err Object, Err.Clear Method, Err.HelpContext Property, Err.Number Property, Chapter 4 |
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
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 |
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
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 |
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
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
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 |
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
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
VBA/VBScript Differences The ExecuteGlobal statement is not supported by VBA. See Also Eval Function, Execute 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
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 |
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 |
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:
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:
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 |
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
See Also FileSystemObject.CopyFile 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
Programming Tips and Gotchas
See Also FileSystemObject.DeleteFile 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
Programming Tips and Gotchas
See Also FileSystemObject.MoveFile 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
See Also FileSystemObject.OpenTextFile Method , TextStream Object |
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 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 |
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 |
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
|
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
Programming Tips and Gotchas
|
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
Programming Tips and Gotchas
See Also FileSystemObject.CopyFolder Method, Folder.Copy 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
Programming Tips and Gotchas
See Also Folder.Copy 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
Programming Tips and Gotchas
See Also Folders.Add 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
Programming Tips and Gotchas
See Also Folder.CreateTextFile Method, TextStream Object |
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
Programming Tips and Gotchas
See Also Folder.Delete 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
Programming Tips and Gotchas
FileSys.DeleteFolder "\NTSERV1d$RootTwo" See Also Folder.Delete 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
Programming Tips and Gotchas
|
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 |
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
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 |
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
Programming Tips and Gotchas
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 |
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
Programming Tips and Gotchas
|
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
See Also FileSystemObject.GetExtensionName 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
Programming Tips and Gotchas
See Also Drives Collection Object |
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
|
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
See Also FileSystemObject.GetBaseName 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
Programming Tips and Gotchas
See Also FileSystemObject.GetFolder Method, FileSystemObject.GetDrive Method, FileSystemObject.OpenTextFile 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
Programming Tips and Gotchas
|
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
Programming Notes
See Also ScriptEngineBuildVersion Function, ScriptEngineMajorVersion Function, ScriptEngineMinorVersion Function |
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
Programming Tips and Gotchas
See Also Folders Collection Object |
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
Programming Tips and Gotchas
|
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:
Programming Tips and Gotchas
|
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
Programming Tips and Gotchas
See Also TextStream Object |
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
|
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
Programming Tips and Gotchas
See Also FileSystemObject.CopyFile Method, FileSystemObject.FileExists Method, FileSystemObject.GetAbsolutePathName 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
Programming Tips and Gotchas
See Also FileSystemObject.CopyFile Method, FileSystemObject.FolderExists Method, FileSystemObject.GetAbsolutePathName 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
Programming Tips and Gotchas
See Also File.OpenAsTextStream Method, TextStream Object |
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
Programming Tips and Gotchas
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 |
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
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 |
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:
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 |
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
Programming Tips and Gotchas
|
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
Programming Tips and Gotchas
See Also FileSystemObject.CreateTextFile Method, TextStream Object |
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
Programming Tips and Gotchas
See Also FileSystemObject.DeleteFile Method, FileSystemObject.DeleteFolder 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
Programming Tips and Gotchas
See Also FileSystemObject.MoveFile Method, FileSystemObject.MoveFolder Method |
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 |
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 |
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
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
See Also 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
Programming Tips and Gotchas
See Also Exit Statement, For . . . Next Statement |
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
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. |
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
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. |
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
Programming Tips and Gotchas
See Also Sub Statement |
Syntax GetLocale( ) Return Value A Long indicating the current locale ID. Description Gets the current locale ID. Rules at a Glance
Programming Tips and Gotchas
VBA/VBScript Differences The GetLocale function is not supported by VBA. See Also SetLocale 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:
Rules at a Glance
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
See Also CreateObject Function, Set Statement |
The VBScript GetRef Function
Programming Tips and Gotchas
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
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
Example |
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
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 |
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
See Also Minute Function, Now Function, Second Function |
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
Programming Tips and Gotchas
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 |
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
Programming Tips and Gotchas
See Also Set Statement, Terminate Event |
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
Programming Tips and Gotchas
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 |
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
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 |
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
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 |
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
Programming Tips and Gotchas
See Also Fix Function |
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
Programming Tips and Gotchas
|
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. |
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
|
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
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. |
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
Programming Tips and Gotchas
|
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
|
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
|
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
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. |
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
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 |
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
VBScript/VB & VBA Differences There is no LCase$ function available in VBScript. See Also UCase Function |
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
Programming Tips and Gotchas
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 |
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
Programming Tips and Gotchas
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. |
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
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
|
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
Programming Tips and Gotchas
|
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
Programming Tips and Gotchas
VB/VBA Differences VBScript does not support the VBA LTrim$ function. See Also RTrim Function, Trim Function |
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 |
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 |
Syntax Me Description The Me Keyword represents the current instance of the class in which code is executing. Rules at a Glance
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
See Also Class Statement |
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
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
VBA/VBScript Differences
See Also Left, LeftB Functions; Len, LenB Functions; Right, RightB Functions |
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 |
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
See Also DatePart Function, Day Function, IsDate Function, MonthName Function, Year 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 |
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
Button Display Constants
Icon Display Constants
Default Button Constants
Modality Constants
Return Values
Programming Tips and Gotchas
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 |
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
See Also Timer 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
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 |
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
Programming Tips and Gotchas
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 |
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
Programming Tips and Gotchas
|
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
Programming Tips and Gotchas
VBA/VBScript Differences
See Also Dim Statement, Public Statement, ReDim Statement, Set 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
Programming Tips and Gotchas
VBA/VBScript Differences
See Also Property Let Statement, Property Set 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
Programming Tips and Gotchas
VBA/VBScript Differences
See Also Property Get 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
Programming Tips and Gotchas
VBA/VBScript Differences
See Also Property Get Statement, Property Let 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
Programming Tips and Gotchas
VBA/VBScript Differences
See Also Private Statement, ReDim Statement, Set Statement |
Syntax Randomize [number] number Use: Optional Data Type: Numeric Any valid numeric expression. Description Initializes the random number generator. Rules at a Glance
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 |
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
Programming Tips and Gotchas
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 |
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:
The RegExp object allows you to search for a substring that matches your pattern string in any of three ways:
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.
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.
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 |
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
Programming Tips and Gotchas
Example See the example for the RegExp.Pattern Property. See Also Matches Collection Object, RegExp.Pattern Property, RegExp.Replace Method, RegExp.Test Method |
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 |
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 |
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.
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.
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 |
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
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 |
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
Programming Tips and Gotchas
See Also RegExp.Execute Method, RegExp.Pattern Property, RegExp.Replace Method |
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
|
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:
Description Replaces a given number of instances of a specified substring in another string. Rules at a Glance
Programming Tips and Gotchas
See Also InStr, InStrB Functions, Mid, MidB Functions |
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
Programming Tips and Gotchas
|
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
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
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 |
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
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
See Also Randomize Sub |
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
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 |
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 |
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:
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 |
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. |
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:
Programming Tips and Gotchas
VBA/VBScript Differences This function is not supported in VBA. See Also ScriptEngineBuildVersion 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
VBA/VBScript Differences This function is not supported in VBA. See Also ScriptEngine Function, ScriptEngineBuildVersion Function, ScriptEngineMajorVersion 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 |
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
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
VBA/VBScript Differences VBA supports two variations of expressionlist that are not supported by VBScript. These are shown in the following table:
See Also If...Then Statement |
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
Programming Tips and Gotchas
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
<% Dim oContact Set oContact = New CContact Response.Write oContact.AddContact %>
Programming Tips and Gotchas
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.
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:
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
If objectvar Is Nothing Then ... 'assignment failed End If
Dim oMainObject Set oMainObject = CreateObject("MainLib.MainObject")
VBA/VBScript Differences
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.
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
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
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: |
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:
Programming Tips and Gotchas
See Also If...Then Statement |
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
|
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
VBA/VBScript Differences VBScript doesn't support the VBA Space$ 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
Programming Tips and Gotchas
See Also Join 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. |
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
Programming Tips and Gotchas
|
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
Programming Tips and Gotchas
VB/VBA Differences VBScript does not support the VBA String$ function. See Also Space 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
|
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
Programming Tips and Gotchas
See Also Call Statement, Exit Statement, Function Statement |
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
|
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
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
See Also Initialize Event, Set Statement |
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 |
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
|
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
See Also TextStream.ReadAll Method , TextStream.ReadLine Method |
Syntax oTextStreamObj.ReadAll Return Value A String. Availability R Description Reads the entire file or input stream into memory. Rules at a Glance
See Also TextStream.Read 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
See Also TextStream.Read Method , TextStream.ReadAll 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
See Also TextStream.SkipLine Method |
Syntax oTextStreamObj.SkipLine Availability R Description Ignores the current line when reading from a text file. Rules at a Glance
|
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 |
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 |
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 |
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 |
Syntax Timer( ) Return Value A Single. Description Returns the number of seconds since midnight. Programming Tips and Gotchas
|
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
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 |
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
Programming Tips and Gotchas
See Also CDate Function, TimeSerial 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 |
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
VBA/VBScript Differences
See Also VarType 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
Programming Tips and Gotchas
See Also LBound 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
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 |
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
VB/VBA Differences This function is not supported in VBA. See Also Escape 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
Programming Tips and Gotchas
VBA/VBScript Differences
See Also TypeName 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
Programming Tips and Gotchas
See Also DatePart Function, Day Function, Month Function, Year 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
Programming Tips and Gotchas
See Also Weekday Function |
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
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 |
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
See Also Do . . . Loop Statement, Set Statement |
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
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