by Drew Kittel
Since its initial release, VBScript has continued to develop and grow from a minimally featured scripting tool into a fairly rich and capable language. This appendix provides a concise yet functional overview and summary reference of VBScript. Some of the things you will find follow:
RESOURCE: A full and complete VBScript language reference and tutorial is available (in HTML format) for free download from the Microsoft VBScript Web page. VBScript capabilities are expanding rapidly, and this reference material is updated frequently as new functions and features are added to VBScript. This documentation provides an excellent online resource for VBScript developers. The site is located at
http://www.microsoft.com/vbscript/
VBScript has quickly evolved into a fairly rich language, complete with the features
one would expect in a full featured language. These include array handling, flow
control, data type conversions, date and time functions, math functions, string operations,
error handling, object creation, and so on. Table C.1 provides a full listing of
VBScript features along with their associated keywords.
Table C.1. VBScript features and keywords.
VBScript Feature Category | Associated Feature or Keyword |
Array handling | Array Dim, Private, Public, ReDim IsArray Erase LBound, UBound |
Assignments | Set |
Comments | Comments using ` or Rem |
Constants and literals | Empty Nothing Null True, False |
Control flow | Do...Loop For...Next For Each...Next If...Then...Else Select Case While...Wend |
Conversions | Abs Asc, AscB, AscW Chr, ChrB, ChrW CBool, Cbyte CCur, Cdate CDbl, Cint CLng, CSng, CStr DateSerial, DateValue Hex, Oct Fix, Int Sgn TimeSerial, TimeValue |
Date and time | Date, Time DateAdd, DateDiff, DatePart DateSerial, DateValue Day, Month, Weekday, Year Hour, Minute, Second Now TimeSerial, TimeValue |
Declarations | Const Dim, Private, Public, ReDim Function, Sub |
Formatting strings | FormatCurrency FormatDateTime FormatNumber FormatPercent |
Error Handling | On Error Err |
I/O | InputBox LoadPicture MsgBox |
Literals | Empty False Nothing Null True |
Math | Atn, Cos, Sin, Tan Exp, Log, Sqr Randomize, Rnd |
Objects | CreateObject Dictionary Err FileSystemObject GetObject TextStream |
Operators | Addition (+), Subtraction (-) Exponentiation (^) Modulus arithmetic (Mod) Multiplication (*), Division (/) Integer division (\) Negation (-) String concatenation (&) Equality (=), Inequality (<>) Less Than (<), Less Than or Equal To (<=) Greater Than (>), Greater Than or Equal To (>=) Is And, Or, Xor Eqv, Imp |
Options | Option Explicit |
Procedures | Call Function, Sub |
Rounding | Abs Int, Fix, Round Sgn |
Script Engine ID | ScriptEngine ScriptEngineBuildVersion ScriptEngineMajorVersion ScriptEngineMinorVersion |
Strings | Asc, AscB, AscW Chr, ChrB, ChrW Filter, Instr, InStrB InstrRev Join Len, LenB LCase, Ucase Left, LeftB Mid, MidB Right, RightB Replace Space Split StrComp String StrReverse LTrim, RTrim, Trim |
Variants | IsArray IsDate IsEmpty IsNull IsNumeric IsObject TypeName VarType |
Table C.2 provides a summary of features found in Visual Basic for Applications
(VBA) but not in VBScript. This table is provided to help experienced VB and
VBA developers determine those familiar features they might not use in VBScript.
Table C.2. Differences between VBA and VBScript.
VBA Feature Category | Associated Feature or Keyword |
Array handling | Option Base Declaring arrays with lower bound <> 0 |
Collection | Add, Count, Item, Remove Access to collections using ! character (for example, MyCollection!Foo) |
Conditional compilation | #Const #If...Then...#Else |
Control flow | DoEvents GoSub...Return, GoTo On Error GoTo On...GoSub, On...GoTo Line numbers, Line labels With...End With |
Conversion | CVar, CVDate Str, Val |
Data types | Every intrinsic data type except Variant Type...End Type |
Date and time | Date and Time statements Timer |
DDE | LinkExecute, LinkPoke, LinkRequest, LinkSend |
Debugging support | Debug.Print End, Stop |
Declaration | Declare (used for declaring DLLs) New Optional ParamArray Property Get, Property Let, Property Set Static |
Error handling | Erl Error On Error...Resume Resume, Resume Next |
File I/O | All basic file I/O |
Financial | All basic financial functions |
Objects | Clipboard Collection |
Object manipulation | TypeOf |
Operators | Like |
Options | Deftype Option Base Option Compare Option Private Module |
Strings | Fixed-length strings LSet, Rset Mid statement StrConv |
Using objects | Collection access using ! |
VBScript provides a number of constants that can be used to specify colors, dates,
MsgBox button settings, file I/O modes, and so on. Using these constants helps to
make your code more readable and easier to maintain. Table C.3 provides a complete
categorized listing of VBScript constants.
Table C.3. VBScript constants.
Category | Name | Description | Value |
Color | vbBlack | Black | &h00 |
vbRed | Red | &hF | |
vbGreen | Green | &hFF00 | |
vbYellow | Yellow | &hFFFF | |
vbBlue | Blue | &hFF0000 | |
vbMagenta | Magenta | &hFF00FF | |
vbCyan | Cyan | &hFFFF00 | |
vbWhite | White | &hFFFFFF | |
Comparison | vbBinaryCompare | Performs binary comparison | 0 |
vbtextCompare | Performs textual comparison | 1 | |
vbDatabaseCompare | Performs comparison based on info in database where Compare is to be performed | 2 | |
Date/Time | vbSunday | Sunday | 1 |
vbMonday | Monday | 2 | |
vbTuesday | Tuesday | 3 | |
vbWednesday | Wednesday | 4 | |
vbThursday | Thursday | 5 | |
vbFriday | Friday | 6 | |
vbSaturday | Saturday | 7 | |
vbFirstJan1 | Default: Uses week where Jan 1 occurs | 1 | |
vbFirstFourDays | Uses first week with at least four days in new year | 2 | |
vbFirstFullWeek | Uses first full week of the year | 3 | |
vbUseSystem | Uses date format in computer's regional settings | 0 | |
vbUseSystemDayOfWeek | Uses system settings for first day of the week | 0 | |
General note for all date constants: date and time displayed are dependent on computer's regional setting |
|||
Date Format | VbGeneralDate | For real number, displays date and time. If no fractional part, displays date only. If no integer part, displays time only. | 0 |
vbLongDate | Date displayed using long date format | 1 | |
vbShortDate | Date displayed using short date format | 2 | |
vbLongTime | Time displayed using long time format | 3 | |
vbShortTime | Time displayed using short time format | 4 | |
File I/O | ForReading | File opened as read-only | 1 |
ForWriting | File opened as read-write. Existing file of same name is overwritten. | 2 | |
ForAppending | File opened for write to EOF | 8 | |
Misc. | vbObjectError | Object error occurred | &h80040000 |
Use the following constants to specify modality and what buttons and icons are displayed |
|||
MsgBox | vbOKOnly | Displays OK button only | 0 |
vbOKCancel | Displays OK and Cancel buttons | 1 | |
vbAbortRetryIgnore | Displays Abort, Retry, and Ignore buttons | 2 | |
vbYesNoCancel | Displays Yes, No, and Cancel buttons | 3 | |
vbYesNo | Displays Yes and No buttons | 4 | |
vbRetryCancel | Displays Retry and Cancel buttons | 5 | |
vbCritical | Displays Critical Message icon | 16 | |
vbQuestion | Displays Warning Query icon | 32 | |
vbExclamation | Displays Warning Message icon | 48 | |
vbInformation | Displays Information Message icon | 64 | |
vbDefaultButton1 | Specifies first button as default | 0 | |
vbDefaultButton2 | Specifies second button as default | 256 | |
vbDefaultButton3 | Specifies third button as default | 512 | |
vbDefaultButton4 | Specifies fourth button as default | 768 | |
vbApplicationModal | Requires user to respond to message box before continuing work in the current application. | 0 | |
vbSystemModal | Requires user to respond to message box before continuing to work in any application. | 4096 | |
Use the following constants to identify the button selected by a user |
|||
MsgBox | VbOK | Selects OK button | 1 |
vbCancel | Selects Cancel button | 2 | |
vbAbort | Selects Abort button | 3 | |
vbRetry | Selects Retry button | 4 | |
vbIgnore | Selects Ignore button | 5 | |
vbYes | Selects Yes button | 6 | |
vbNo | Selects No button | 7 | |
String | vbCr | Carriage return | Chr(13) |
vbCrLf | Carriage return, linefeed combination | Chr(13) & Chr(10) | |
vbFormFeed | Form feed | Chr(10) | |
vbLf | Line feed | Chr(10) | |
vbNewLine | Newline character (platform specific) | Chr(13) & Chr(10) or Chr(10) | |
vbNullChar | Character with a value of 0 | Chr(0) | |
vbNullString | Calls external procedures. This is not a zero-length string! | Zero-valued string | |
vbTab | Horizontal tab | Chr(9) | |
vbVerticalTab | Vertical tab | Chr(11) | |
Tristate | TristateTrue | True | -1 |
TristateFalse | False | 0 | |
TristateUseDefault | Use default setting | 2 | |
VarType | vbEmpty | Uninitialized by default | 0 |
vbNull | Contains no valid data | 1 | |
vbInteger | Integer subtype | 2 | |
vbLong | Long subtype | 3 | |
vbSingle | Single subtype | 4 | |
vbDouble | Double subtype | 5 | |
vbCurrency | Currency subtype | 6 | |
vbDate | Date subtype | 7 | |
vbString | String subtype | 8 | |
vbObject | Object | 9 | |
vbError | Error subtype | 10 | |
vbBoolean | Boolean subtype | 11 | |
vbVariant | Variant; used only for arrays of variants | 12 | |
vbDataObject | Data-access object | 13 | |
vbDecimal | Decimal subtype | 14 | |
vbByte | Byte subtype | 17 | |
vbArray | Array | 8192 |
VBScript provides a complete set of operators, including arithmetic operators,
comparison operators, concatenation operators, and logical operators. Table C.4 provides
a listing of all VBScript operators along with brief descriptions of each.
Table C.4. VBScript operators.
VBScript Operator | Syntax and Description | |||||||||||||||||||||||||||||||||||||||||||||||||
+ | result = expression1 + expression2 | |||||||||||||||||||||||||||||||||||||||||||||||||
Sums two numbers. Can also be used to concatenate strings (although the & operator is recommended for this). | ||||||||||||||||||||||||||||||||||||||||||||||||||
And | result = expression1 And expression2 | |||||||||||||||||||||||||||||||||||||||||||||||||
Performs logical conjunction (and-ing) on two expressions. result evaluates to True only if both expressions are true. result evaluates to Null if either expression is Null. | ||||||||||||||||||||||||||||||||||||||||||||||||||
& | result = expression1 & expression2 | |||||||||||||||||||||||||||||||||||||||||||||||||
Forces string concatenation of two expressions. If an expression is not a string, it is converted to String. If one expression is Null, it is treated as a zero-length string. If both expressions are Null, result is Null. Empty expressions are treated as Null strings. | ||||||||||||||||||||||||||||||||||||||||||||||||||
/ | result = number1/number2 | |||||||||||||||||||||||||||||||||||||||||||||||||
Divides two numbers and returns floating-point results. If both expressions are Null, result is Null. Empty expressions are treated as 0. | ||||||||||||||||||||||||||||||||||||||||||||||||||
Eqv | result = expression1 Eqv expression2 | |||||||||||||||||||||||||||||||||||||||||||||||||
Performs logical equivalence on two expressions (using a bitwise comparison). If either expression is Null, result is Null. If both expressions are True or both expressions are False, result is True; otherwise, result is False. | ||||||||||||||||||||||||||||||||||||||||||||||||||
^ | result = number^exponent | |||||||||||||||||||||||||||||||||||||||||||||||||
Raises number to the power of an exponent. If number or exponent is Null, result is Null. If > 1, exponentiation is performed; ^ is evaluated left to right. number can be negative only if exponent is an integer value. | ||||||||||||||||||||||||||||||||||||||||||||||||||
Imp | result = expression1 Imp expression2 | |||||||||||||||||||||||||||||||||||||||||||||||||
Performs a logical implication on two expressions (using a bitwise
comparison). The following table summarizes how result is determined:
|
||||||||||||||||||||||||||||||||||||||||||||||||||
\ | result = number1\number2 | |||||||||||||||||||||||||||||||||||||||||||||||||
Divides two numbers and returns an integer result. If an expression is Null, result is Null. Empty expressions are treated as 0. expressions are rounded to btye, integer, or long subtypes prior to division. | ||||||||||||||||||||||||||||||||||||||||||||||||||
Is | result = object1 Is object2 | |||||||||||||||||||||||||||||||||||||||||||||||||
Compares two reference objects. If object1 and object2 refer to the same object, result is True; otherwise, result is False. | ||||||||||||||||||||||||||||||||||||||||||||||||||
Mod | result = number1 Mod number2 | |||||||||||||||||||||||||||||||||||||||||||||||||
Divides two numbers and returns the remainder. Floating-point numbers first are rounded to integers. If an expression is Null, result is Null. Empty expressions are treated as 0. | ||||||||||||||||||||||||||||||||||||||||||||||||||
* | result = number1*number2 | |||||||||||||||||||||||||||||||||||||||||||||||||
Multiplies two numbers. If either expression is Null, result is Null. Empty expressions are treated as 0. | ||||||||||||||||||||||||||||||||||||||||||||||||||
- | result = number1-number2 or -number | |||||||||||||||||||||||||||||||||||||||||||||||||
Finds the difference of two numbers or negates the value of a number (in this case, it is a unary operation). If either expression is Null, result is Null. Empty expressions are treated as 0. | ||||||||||||||||||||||||||||||||||||||||||||||||||
Not | result = Not expression | |||||||||||||||||||||||||||||||||||||||||||||||||
Performs a logical negation on an expression. Negating a Null expression results in a Null result. | ||||||||||||||||||||||||||||||||||||||||||||||||||
Or | result = expression1 Or expression2 | |||||||||||||||||||||||||||||||||||||||||||||||||
Performs a logical disjunction (or-ing) on two expressions (using a bitwise comparison). | ||||||||||||||||||||||||||||||||||||||||||||||||||
If either expression evaluates to True, the result is True. | ||||||||||||||||||||||||||||||||||||||||||||||||||
Xor | result = expression1 Xor expression2 Performs a logical exclusion (exclusive or-ing) on two expressions (using a bitwise comparison). If only one of the expressions is True, result is True. But, if either expression is Null, result is Null. |
Table C.5 provides a listing of all VBScript functions that exist as of this writing.
The table provides brief descriptions along with the required function syntaxes.
Table C.5. VBScript functions.
VBScript Function | Syntax and Description | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Abs | Abs(number) Returns the absolute value (the unsigned magnitude) of a number or expression. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Array | Array(arglist) Returns a variant containing an array. arglist is a comma-delimited list of values assigned to elements of an array contained with the variant. A sample use follows: Dim A ` create variable named A A = Array(10,20,20) ` assign an array to A B = A(2) ` assign value in 2nd element to B |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Asc | Asc(string) Returns the ANSI character code for the first letter in string. Notes: Use AscB for use with byte data contained in a string; AscB returns the first byte instead of the character code. Use AscW for 32-bit platforms using Unicode characters; AscW returns the Unicode (wide) character code. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Atn | Atn(number) Returns the arctangent of number in radians. Result is in the range of -pi/2 to pi/2 radians. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
CBool | Cbool(expression) Returns an expression converted to the Boolean subtype of Variant. If expression is 0, False is returned; otherwise, True is returned. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
CByte | Cbtye(expression) Returns an expression converted to the Byte subtype of Variant. Use CByte to provide internationally aware conversions from any other data type to a Byte subtype (different decimal separators are recognized properly depending on the locale setting of your system). |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
CCur | Ccur(expression) Returns an expression converted to the Currency subtype of Variant. Use CCur to provide internationally aware conversions from any other data type to a Currency subtype (different decimal separators and thousands separators are recognized properly depending on the locale setting of your system). |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
CDate | Cdate(date) Returns an expression converted to the Date subtype of Variant. CDate recognizes date formats according to your system's locale setting. IsDate should be used to see whether date can be converted to a date or time. CDate accepts date and time literals as well as some numbers falling within valid date ranges (when converting numbers to dates, the whole number part is converted to a date, while any fractional part is converted to a time). |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
CDbl | Cdbl(expression) Returns an expression converted to the Double subtype of Variant. Use CDbl to provide internationally aware conversions from any other data type to a Double subtype (different decimal separators and thousands separators are recognized properly depending on the locale setting of your system). |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Chr | Chr(charcode) Returns the character associated with the ANSI charcode. Notes: Use ChrB for use with byte data contained in a string; ChrB returns the first byte instead of the character code. Use ChrW for 32-bit platforms using Unicode characters; ChrW returns the Unicode (wide) character code. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
CInt | Cint(expression) Returns an expression converted to the Integer subtype of Variant. Unlike Fix and Int, CInt rounds to the nearest even number rather than truncating. Use CInt to provide internationally aware conversions from any other data type to an Integer subtype (different decimal separators and thousands separators are recognized properly depending on the locale setting of your system). |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
CLng | Clng(expression) Returns an expression converted to the Long subtype of Variant. Unlike Fix and Int, CLong rounds to the nearest even number rather than truncating. Use CLong to provide internationally aware conversions from any other data type to an Integer subtype (different decimal separators and thousands separators are recognized properly depending on the locale setting of your system). |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Cos | Cos(number) Returns the cosine of an angle. number should be expressed in radians. The result is in the range of -1 to 1. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
CreateObject | CreateObject(class) The class argument uses the syntax servername.typename. servername is the name of the application providing the object. typename is the type/class of the object to create. Creates and returns a reference to an Automation object. The following example illustrates how you can create an Excel spreadsheet object and its methods and properties accessed: Dim ExcelSSheet Set ExcelSSheet = CreateObject("Excel.Sheet") ` Make Excel visible through Application object. ' Place text in first cell of the sheet. ' Save the sheet. ' Close Excel with the Quit method on the Application object. ' Release the object variable. ExcelSheet.Application.Visible - True ExcelSheet.Cells(1,1).Value = "This is col A, row1" ExcelSheet.SaveAs "D:\MyDocs\SSTEST.DOC" ExcelSheet.Application.Quit Set ExcelSheet = Nothing |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
CSng | Csng(expression) Returns an expression converted to the Single subtype of Variant. Use CSng to provide internationally aware conversions from any other data type to a Single subtype (different decimal separators and thousands separators are recognized properly depending on the locale setting of your system). |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
CStr | Cstr(expression) Returns an expression converted to the String subtype of Variant. The data in expression determines the result per the following:
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Date | Date Returns the current system date. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
DateAdd | DateAdd(interval, number, date) Adds or subtracts the specified time interval from date. interval is a string expression for the interval you want to add. interval can have the following values:
number is a numeric expression for the number of the interval to add (positive for future dates, negative for past). date is a Variant or literal representing the date interval is added to. The following example illustrates its usage: ' add one month to January 31 '29-Feb-96 returned because 1996 is a leap year NewDate = DateAdd("m", 1, "31-Jan-95") |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
DateDiff | DateDiff(interval, date1, date2 [,firstdayofweek[,
firstweekofyear]]) Determines how many specified time intervals (number of days or weeks) exist between two dates. interval is a string expression for the interval you want to use to calculate the differences between date1 and date2 (see DateAdd for valid values). date1, date2 are date expressions to use in the calculation. firstdayofweek is a constant specifying the day of week (if not specified, Sunday is assumed). Following are valid constant names, values, and descriptions:
firstweekofyear is a constant specifying the first week of the year (if not specified, it is assumed to be the week in which Jan 1 occurs). Following are valid constant names, values, and descriptions:
To calculate the number of days between date1 and date2, you can use Day of year ("y") or Day ("d"). When interval is Weekday ("w"), DateDiff returns the number of weeks between the two dates. If date1 falls on a Monday, DateDiff counts the number of Mondays until date2. It counts date2 but not date1. If interval is Week ("ww"), however, the DateDiff function returns the number of calendar weeks between the two dates. It counts the number of Sundays between date1 and date2. DateDiff counts date2 if it falls on a Sunday, but it doesn't count date1, even if it does fall on a Sunday. If date1 refers to a later point in time than date2, the DateDiff function returns a negative number. The firstdayofweek argument affects calculations that use the "w" and "ww" interval symbols. If date1 or date2 is a date literal, the specified year becomes a permanent part of that date. However, if date1 or date2 is enclosed in quotation marks (" ") and you omit the year, the current year is inserted into your code each time the date1 or date2 expression is evaluated. This makes it possible to write code that can be used in different years. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
DatePart | DatePart(interval, date[, firstdayofweek[,firstweekofyear]])
Evaluates a date and returns a specific interval of time. interval is a string expression for the interval you want to return. date is the date expression to evaluate. firstdayofweek is a constant specifying the day of week (if not specified, Sunday is assumed). See DateDiff for valid values. firstweekofyear is a constant specifying the first week of the year (if not specified, it is assumed to be the week in which Jan 1 occurs). See DateDiff for valid values. The firstdayofweek argument affects calculations that use the "w" and "ww" interval symbols. If date is a date literal, the specified year becomes a permanent part of that date. However, if date is enclosed in quotation marks (" ") and you omit the year, the current year is inserted into your code each time the date expression is evaluated. This makes it possible to write code that can be used in different years. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
DateSerial | DateSerial(year, month, day) Returns a Variant of subtype Date for the specified year, month, and day. year is a number (or numeric expression) from 100 through 9999. month, day are numeric expressions (with values in the range of 1-12 and 1-31, respectively). Relative dates can be used for the arguments using any numeric expression that represents some number of days, months, or years before or after a certain date. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
DateValue | DateValue(date) Returns a Variant of subtype Date. date can be any expression that represents a date/time in the range of January 1, 100 through December 31, 9999. date is usually a string expression. If date is a string that includes only numbers separated by valid date separators, DateValue recognizes the order for month, day, and year per your system's Short Date format and unambiguous dates containing month names, either in long or abbreviated form (for example, 12/30/1991; 12/30/91; December 30, 1991; and Dec 30, 1991). If date has no year part, the year from the system's date is used. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Day | Day(date) Returns a whole number between 1 and 31 that represents the day of the month. date is any argument that can represent a valid date. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Exp | Exp(number) Returns e (base of natural logarithms) raised to a power. number should not exceed 709.782712893. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Filter | Filter(InputStrings, Value[, Include[, Compare]])
Returns a zero-based array containing a subset of a string array based on a specified filter criteria. The return array is sized to hold only the number of matched items. If no matches are found, an empty array is returned. An error occurs if InputStrings is not one-dimensional or is Null. Value is a string to search for in the one-dimensional array of strings InputStrings. Include is an optional Boolean value. If True, Filter returns the subset of the array that contains Value as a substring. If False, Filter returns the subset of the array that does not contain Value as a substring. Compare is an optional numeric value that indicates the type of string comparison to be used. The following are valid numeric names, values, and descriptions:
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Fix | Fix(number) Returns the integer portion of number (the fractional part is removed and the resultant integer value is returned). For example, -8.4 is converted to -8 while 8.4 is converted to 8. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
FormatCurrency | FormatCurrency(Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit
[,UseParensForNegativeNumbers [,GroupDigits]]]]) Uses the currency symbol defined in the system Control Panel to return an expression formatted as a currency value. Expression is the only required argument and represents the expression to be formatted. NumDigitsAfterDecimal is an optional numeric value indicating the number of places to the right of the decimal to be displayed (default is -1, indicating that the computer's regional settings are used). IncludeLeadingDigit is an optional Tristate constant that indicates whether the leading zero is displayed for fractional values. UseParensForNegativeNumbers is an optional Tristate constant that indicates whether negative values are to be placed within parentheses. GroupDigits is an optional Tristate constant that indicates whether numbers are grouped using the group delimiter specified by the computer's regional settings. Following are valid Tristate constant names, values, and descriptions:
When optional arguments are omitted, values for those arguments are provided by the computer's regional settings. The position of the currency symbol relative to the currency value is determined by the system's regional settings. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
FormatDateTime | FormatDateTime(Date[,NamedFormat]) Returns Date (a Date expression) formatted as a date or time. NamedFormat is an optional numeric value used to specify the date/time format used (vbGeneralDate is used by default if this argument is omitted). Following are valid constant names, values, and descriptions:
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
FormatNumber | FormatNumber(Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit
[,UseParensForNegativeNumbers [,GroupDigits]]]]) Returns Expression formatted as a number. See FormatCurrency for a description of arguments. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
FormatPercent | FormatPercent(Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit
[,UseParensForNegativeNumbers [,GroupDigits]]]]) Returns Expression formatted as a percentage (multiplied by 100) with a trailing % character. See FormatCurrency for a description of arguments. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GetObject | GetObject([pathname] [, class]) Accesses an ActiveX object from a file and assigns the object to an object variable. It is used when there is a current instance of the object or if you want to create the object with a file already loaded. If no current instance exists and you don't want the object started with a file loaded, use the CreateObject function instead. Note that, for objects registered as a single-instance object, only one instance of the object is created, regardless of how many times CreateObject is executed. With single-instance objects, GetObject always returns the same instance when called with the zero-length string ("") syntax. pathname is an optional string that specifies the full path and name of the file that con-tains the object being retrieved. If omitted, class is required. class is an optional string specifying the object. It has the syntax appname.objectype where appname is the name of the application providing the object and objectype is the type or class of object to create. The following examples illustrate how GetObject can be used. When Dim CADObject Set CADObject = GetObject("C:\CAD\SCHEMA.CAD") is executed, the application associated with the specified pathname is started and the object in the specified file is activated. If pathname is a zero-length string or is omitted, class is required and GetObject returns a new object instance of the specified type or a currently active object of the specified type, respectively. Some applications allow activation of part of a file by adding an exclamation point (!) to the end of the filename and following it with a string that identifies the part of the file you want to activate. You might activate a layer within a drawing as follows, for example: Set LayerObject = GetObject("C:\CAD\SCHEMA.CAD!Layer3") To specify which object in a file you want to activate, use the optional class argument--for example: Dim MyObject Set MyObject = GetObject("C:\DRAWINGS\SAMPLE.DRW", "FIGMENT.DRAWING" Finally, properties and methods of the object in the preceding code can be accessed as shown here: MyObject.Line 9, 90 MyObject.InsertText 9, 100, "Hello, world." MyObject.SaveAs "C:\DRAWINGS\SAMPLE.DRW" |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Hex | Hex(number) Returns a string representing the hexadecimal value of number. If number is Null, Hex returns Null. If number is Empty, Hex returns 0. If number is not a whole number, it is rounded to the nearest whole number prior to evaluation. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Hour | Hour(time) Returns a whole number from 0 through 23 that represents the hour of the day. The time argument is any expression that can represent a time. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
InputBox | InputBox(prompt[, title][, default][, xpos][, ypos][,
helpfile, context]) Displays a prompt in a dialog box, waits for the user to input text or choose a button, and returns the contents of the textbox after the user clicks OK or presses Enter. If the user clicks Cancel, the function returns a zero-length string (""). prompt is a string expression with a maximum length of 1,024 characters. Lines can be separated by using the carriage-return character (Chr(13)), linefeed character (Chr(10)), or a combination of both (Chr(13)& Chr(10)) between lines. title is a string expression to be displayed in the title bar of the dialog box. If omitted, the application name is used. default is an optional string expression to be displayed in the textbox if no other input is provided. xpos, ypos are numeric expressions that specify the distance (in twips) of the left and upper edges of the dialog box from the left and top edges of the screen, respectively. If xpos is omitted, the box is centered horizontally; if ypos is omitted, the box is positioned approximately one-third from the top of the screen. helpfile is a string expression specifying the context-sensitive Help file to use for the dialog box. If provided, context also must be supplied. context is a numeric expression that identifies the author-assigned Help context number for the appropriate topic. If provided, helpfile also must be provided. When both helpfile and context are supplied, a Help button is added automatically to the dialog box. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
InStr | InStr([start, ]string1, string2[, compare]) Returns the position of the first occurrence of string2 string within string1. start is an optional numeric expression that specifies where the search starts (if omitted, searches start at the first character). string1 is the string being searched, whereas string2 is the string being searched for. compare is an optional numeric expression specifying the kind of comparison to use (if omitted, binary is the default). Following are valid constant names, values, and descriptions for compare:
Following are InStr return values:
Note: Use InStrB with byte data contained in a string. InStrB returns the byte position of the first occurrence of one string within another. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
InStrRev | InstrRev(string1, string2[, start[, compare]]) Returns the position (from the end of the string) of the first occurrence of string2 string within string1. See InStr for value of compare and return values. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Int | Int(number) Returns the integer portion of number (the fractional part is removed and the resultant integer value returned). For example, -8.4 is converted to -9 (contrast this with the behavior of Fix), whereas 8.4 is converted to 8. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
IsArray | IsArray(varname) Returns a Boolean True value if varname is an array; returns False otherwise. Useful with variants containing arrays. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
IsDate | IsDate(expression) Returns a Boolean True value if expression is a date (or can be converted to one); returns False otherwise. Valid dates for MS Windows range from January 1, 100 A.D. through December 31, 9999 A.D. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
IsEmpty | IsEmpty(expression) Returns a Boolean True value if expression (typically, a single variable) is uninitialized (or is explicitly set to Empty); returns False otherwise. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
IsNull | IsNull(expression) Returns a Boolean True if expression is Null (contains no valid data); returns False otherwise. If expression consists of more than one variable, any of which are Null, then True is returned. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
IsNumeric | IsNumeric(expression) Returns a Boolean True if expression is recognized as a number; returns False otherwise. Note: If expression is a date expression, False is returned. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
IsObject | IsObject(expression) Returns a Boolean True if expression references a valid Automation object (if expression is a variable of Object subtype or a user-defined object); returns False otherwise. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Join | Join(list[, delimiter]) Returns a string created by joining a number of substrings (delimited by the optional delimiter character) contained in the array list. If delimiter is "", substrings are concatenated without delimiters. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
LBound | LBound(arrayname[, dimension]) Returns the smallest available subscript for the array for the given dimension (1 for first dimension, 2 for second, and so on). Used with UBound to determine the size of an array. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
LCase | Lcase(string) Returns a string in which uppercase characters of string are converted to lowercase (non-letter characters are unaffected). If string is Null, Null is returned. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Left | Left(string, length) Returns a specified number of characters (length) from the left side of string. If string is Null, Null is returned. If length exceeds the number of characters in string, the entire string is returned. LeftB should be used for byte data contained in a string. In this case, length refers to a number of bytes. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Len | Len(string | varname) Returns the number of characters in a string or the number of bytes necessary to store a variable. If string or varname contains Null, Null is returned. LenB should be used for byte data contained in a string. In this case, LenB returns the number of bytes used to represent the string. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
LoadPicture | LoadPicture(picturename) Returns a picture object. Picture name is a string expression specifying the name of a picture file to load. Recognized formats are bitmap (.bmp), icon (.ico), run-length encoded (.rle), standard and enhanced metafiles (.wmf and .emf), GIF (.gif), and JPEG (.jpg). |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Log | Log(number) Returns the natural logarithm (the logarithm to the base e) of number. number must be greater than 0. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
LTrim | Ltrim(string) Returns a copy of string without leading spaces. If string is Null, Null is returned. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Mid | Mid(string, start[, length]) Returns a specified number of characters from string (beginning at the character position indicated by start). If start is greater than the number of characters in string, "" is returned. MidB should be used for byte data contained in a string. In this case, function arguments specify numbers of bytes. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Minute | Minute(time) Returns a whole number from 0 through 59 that represents the minute of the hour. time can be any expression that represents a time. If time contains Null, Null is returned. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Month | Month(date) Returns a whole number from 1 through 12 that represents the month of the year. date can be any expression that represents a date. If date contains Null, Null is returned. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
MonthName | MonthName(month[, abbreviate]) Returns a string indicating the month specified by month (January for 1, February for 2, and so on). If abbreviate is a Boolean True, the string returned contains an abbreviated month name. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
MsgBox | MsgBox(prompt[, buttons][, title][, helpfile, context])
Displays a message in a dialog box, waits for the user to click a button, and
returns a value indicating which button the user clicked. prompt
is a string expression for the message to be displayed. Lines in a multiline message
can be separated by using a CR (Chr(13)), LF (Chr(10)), or CR-LF
pair. prompt is limited to (approximately) 1,024 characters. buttons
is a numeric expression that is a summation of values that specifies the types of
buttons to display, modality, icon style, and default button (if omitted, 0
is the default). title is a string expression for the dialog box
bar title to be displayed (if omitted, the application name is used). helpfile
is a string expression that identifies the context-sensitive Help file to use (if
provided, context is required). This is not available on 16-bit platforms.
context is a numeric expression identifying the help context number
assigned to a Help topic (if provided, context is required). This
is not available on 16-bit platforms. Following are MsgBox button
argument settings used to specify buttons displayed, icon styles, default buttons,
and dialog box modality:
Following are MsgBox return values indicating which button was clicked:
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Now | Now Returns the current date and time per your computer's system date/time. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Oct | Oct(number) Returns a string representing the octal value of number. If number is Null, Null is returned. If number is Empty, 0 is returned. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Replace | Replace(expression, find, replacewith[, start[, count[,
compare]]]) Returns a string in which a specified substring has been replaced with another substring a specified number of times. expression is the string expression containing the substring to be replaced. find is the substring to search for. replacewith is the substring used to replace the find substring. start is an optional value indicating the position within substring where the search begins (if omitted, 1 is used). count is an optional value indicating the number of replacements to make (if omitted, -1 is used to perform all possible replacements). compare is an optional numeric expression specifying the kind of comparison to use (if omitted, binary is the default). Following are valid constant names, values, and descriptions for compare:
Following are Replace return values:
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Right | Right(string, length) Returns the number of characters (specified by length) from the right side of string. If length is 0, "" is returned. If length exceeds the length of string, the entire string is returned. RightB should be used for byte data contained in a string. In this case, length specifies the number of bytes. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Rnd | Rnd[(number)] Returns a random number using number as a seed. The value of number determines how Rnd generates a random number as the following:
Note: For any given seed, the same number sequence is generated (Rnd uses the previous number as a seed for each successive number in a sequence). Therefore, you should use Randomize with no arguments to initialize the random number generator with a seed derived from the system timer. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Round | Round(expression[, numdecimalplaces]) Returns a number rounded to a number of decimal places. numdecimalplaces specifies the number of places to the right of the decimal to be included in the rounding. If not specified, integers are returned. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
RTrim | Rtrim(string) Returns a copy of string without trailing spaces. If string is Null, Null is returned. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ScriptEngine | ScriptEngine Returns a string representing the scripting language in use. Possible values are VBScript, VBA, or JScript. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ScriptEngine- BuildVersion | ScriptEngineBuildVersion Returns the build version number of the script engine in use (this corresponds to the version information in the DLL for the scripting language in use). |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ScriptEngine- MajorVersion | ScriptEngineMajorVersion Returns the major version number of the script engine in use (this corresponds to the version information in the DLL for the scripting language in use). |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ScriptEngine- MinorVersion | ScriptEngineMinorVersion Returns the minor version number of the script engine in use (this corresponds to the version information in the DLL for the scripting language in use). |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Second | Second(time) Returns a whole number from 0 through 59 that represents the second of the minute. If time is Null, Null is returned. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Sgn | Sgn(number) Returns an integer indicating the sign of number (1 if number is positive, -1 if number is negative, 0 if number is 0). |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Sin | Sin(number) Returns the sine of number (which is an angle represented in radians). The result is in the range of -1 to 1. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Space | Space(number) Returns a string of spaces of the length specified by number. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Split | Split(expression[, delimiter[, count[, compare]]])
Returns a one-dimensional array that contains count number of substrings. The array is zero-based. expression is a string expression that contains substrings and delimiters. Note that if expression is zero-length, Split returns an empty array. delimiter is an optional string character that defines the limits if substrings are in expression (if omitted, the space character is used by default). If a zero-length string character is used, Split returns a one-element array containing expression. count is an optional value that specifies the number of substrings to return (if omitted, -1 is used to indicate that all strings are returned). compare is an optional numeric expression specifying the kind of comparison to use (if omitted, binary is the default). Following are valid constant names, values, and descriptions for compare:
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Sqr | Sqr(number) Returns the square root of number. number must be greater than or equal to 0. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
StrComp | StrComp(string1, string2[, compare]) Returns a value indicating the result of a comparison between string1 and string2. string1 and string2 are any valid string expressions (these are required arguments). compare is an optional numeric expression specifying the kind of comparison to use (if omitted, binary is the default). See Split for valid values of compare. Some StrComp return values follow:
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
StrReverse | StrReverse(string1) Returns a string in which the character order of string1 is reversed. If string1 is "", then "" is returned. If string1 is Null, an error occurs. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
String | String(number, character) Returns a string of length specified by number consisting of characters specified by character. If number or character is Null, Null is returned. If character is a string, its first character is used to construct the return string. If a number greater than 255 is used for character, it is converted to a valid character code using character Mod 256. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Tan | Tan(number) Returns the tangent of number (which is an angle represented in radians). |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Time | Time Returns a Variant of subtype Date that indicates the current system time. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
TimeSerial | TimeSerial(hour, minute, second) Returns a Variant of subtype Date containing the time for the specified hour, minute, and second. hour is a number/numeric expression from 0 to 23 (12 a.m. to 11 p.m.). minute and second are number/numeric expressions from 0 through 59. Relative times can be specified--for example, TimeSerial(12 - 6, -15, 0) returns a time for 15 minutes before (-15) six hours before noon (12 - 6), or 5:45:00 a.m. If any argument exceeds the accepted range for that argument, it is incremented to the next larger unit as appropriate. For example, 75 minutes is evaluated as one hour and 15 minutes. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
TimeValue | TimeValue(time) Returns a Variant of subtype Date that contains the time. time is typically a string expression representing a time from 0:00:00 (12:00:00 a.m.) through 23:59:59 (11:59:59 p.m.). If time is Null, Null is returned. If time contains date information, it is not returned by TimeValue (however, if the date information is not valid, an error occurs). |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Trim | Trim(string) Returns a copy of string without leading and trailing spaces. If string is Null, Null is returned. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
TypeName | TypeName(varname) Returns the Variant subtype of varname. varname can be any variable. This is a required argument. Return values can be any of the following self-explanatory values: Byte, Integer, Long, Single, Double, Currency, Decimal, Date, String, Boolean, Empty, Null, Object, or Error. Other possible return values are <object type> (the actual type name of an object), Unknown (an unknown object type), or Nothing (an object variable that doesn't refer to an object instance). |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
UBound | UBound(arrayname[, dimension]) Returns the largest available subscript for the indicated dimension of an array. arrayname is the name of the array (this is required). dimension is an optional number that indicates which array dimension's bound is returned (for example, 1 for the first dimension and so on). If omitted, 1 is used. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
UCase | Ucase(string) Returns a string in which lowercase characters of string are converted to uppercase (non-letter characters are unaffected). If string is Null, Null is returned. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
VarType | VarType(varname) Returns a value that indicates the subtype of varname. varname can be any variable. VarType return values follow:
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Weekday | Weekday(date, [firstdayofweek]) Returns a whole number representing the day of the week. date is any expression that can represent a date (if Null, date returns Null). firstdayofweek is a constant that specifies the first day of the week (vbSunday is assumed if this is omitted). Valid settings for firstdayofweek follow:
Weekday can return the values vbSunday, vbMonday, vbTuesday, vbWednesday, vbThursday, vbFriday, or vbSaturday. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
WeekdayName | WeekDayName(weekday, abbreviate, firstdayofweek) weekday is a required numeric designation for the day of the week. The numeric value of each day depends on the firstdayofweek setting. abbreviate is an optional Boolean value that indicates whether the weekday name should be abbreviated. False (no abbreviation) is assumed if this is omitted. firstdayofweek is a constant that specifies the first day of the week (vbSunday is assumed if this is omitted). See Weekday for valid settings for firstdayofweek. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Year | Year(date) Returns a whole number that represents the year. If date is Null, Null is returned. |
VBScript provides a complete set of statements that can be used to define variables,
call subprocedures or functions, assign values to variables, exit programs, and control
program flow (looping, conditional execution, case statements, and so on). Table
C.6 provides a listing of all VBScript statements along with brief descriptions.
Table C.6. VBScript statements.
VBScript Statement | Syntax and Description |
Call | [Call] name [argumentlist] Transfers control to a subprocedure or function. Use is optional, but if used, argumentlist must be enclosed in parentheses. |
Const | [Public | Private] Const constname = expression Declares constants for use in place of literal values. Public and Private keywords are optional and available only at the script level (not within procedures). Public declares constants available to all procedures in all scripts, whereas Private declares constants available only within the script where the declaration was made. |
Dim | Dim varname[([subscripts])][, varname[([subscripts])]]
... The subscripts argument uses the following syntax:
upperbound [,upperbound] ... Arrays of up to 60 dimensions can be declared. Array indexing starts at 0. Use Dim with empty parentheses to declare a dynamic array. Then use ReDim within a procedure to define the number of dimensions and elements. Numeric variables are initialized to 0. Strings are initialized to "" (zero-length). Do...Loop Do [{While | Until} condition] [statements] [Exit Do] [statements] Loop or Do [statements] [Exit Do] [statements] Loop [{While | Until} condition] Repeats a block of statements while a condition is True or until a condition becomes True. Exit Do transfers control to the loop that is one nested level above the loop where it occurs. |
Erase | Erase array Reinitializes elements in fixed-size arrays as in the following: Elements of numeric arrays are set to 0 Elements of string arrays are set to "" Elements of object arrays are set to the special value Nothing If the array is a dynamic array, memory used by the array is freed. |
Exit | Four syntactical forms are available: Exit Do Provides a means for exiting a Do Loop statement. Transfers control to the statement following the Loop statement unless it is in a nested loop, in which case transfers control to the loop that is one nested level above the loop where it occurs. Exit For Provides a means for exiting a For loop. Transfers control to the statement following the Next statement unless it is in a nested loop, in which case transfers control to the loop that is one nested level above the loop where it occurs. Exit Function Causes immediate exit from the Function procedure where it appears. Exit Sub Causes immediate exit from the subprocedure where it appears. |
For...Next | For counter = start To end [Step step] [statements] [Exit For] [statements] Next Repeats a group of statements a specified number of times. step specifies how the counter value is changed for each loop. step can be positive or negative. If step is positive (or 0), the loop executes while counter is <= end. If step is negative, the loop executes while counter is >= end. |
For Each...Next | For Each element In group [statements] [Exit For] [statements] Next [element] Repeats a group of statements for each element in an array or collection. For arrays, element must be a Variant variable. For collections, element can be only a Variant, Object, or Automation object variable. |
Function | [Public | Private] Function name [(arglist)] [statements] [name = expression] [Exit Function] [statements] [name = expression] End Function Declares the name, arguments, and code that form the body of a Function procedure. Function procedures are public by default (if not specified with Public or Private) and thus visible to all other procedures in your script. Function procedures can't be contained inside another Function or Sub procedure. Unlike Sub procedures, Function procedures can exist on the right side of an expression. Function procedures can be called. See Call for information. Public indicates that the Function procedure is accessible to all other procedures in all scripts. Private indicates that the Function procedure is accessible only to other procedures in the script where it is declared. name is the function name. arglist is the list of variables (comma-separated) passed to the procedure. arglist has the syntax [ByVal | ByRef] varname[( )] where ByVal and ByRef indicate that an argument is passed by value and reference, respectively and varname is the variable representing the argument. statements are statement groups to be executed. expression is the return value assigned to the function name. Exit Function statements can appear anywhere in a Function procedure and cause an immediate exit from a Function procedure. The following example shows how to assign a return value to a function named BinSearch (note that if no value is assigned to a function name, the procedure returns a default value; numeric functions return 0, string functions return (""), and functions that return object references return Nothing): Function BinSearch(. . .) ... If lower > upper Then ` Return a value of False. BinSearch = False Exit Function End If ... End Function Caution: Function procedures can be called recursively. However, recursion can lead to stack overflow. A procedure can use a variable that is not explicitly declared in the procedure, but a naming conflict can occur if anything you have defined at the script level has the same name (use of Option Explicit is a good practice). VBScript may rearrange arithmetic expressions to increase internal efficiency, so avoid using a Function procedure in an arithmetic expression when the function changes the value of variables in the same expression. |
If...Then...Else | If condition Then [statements] [ElseIf condition-n Then [elseifstatements]] . . . [Else [elsestatements]] End If Conditionally executes a group of statements (depending on the value of an expression). If condition is True, the statements following Then are executed. If otherwise, each ElseIf (if any) is evaluated in turn, and its subsequent statements are executed if the condition is True. Else and ElseIf are both optional, and you can have as many ElseIf statements as desired. condition (and condition-n) is a numeric or string expression that evaluates to True or False (if Null, condition is treated as False). Alternatively, condition can be an expression of the form TypeOf objectname Is objecttype, where objectname is an object reference and objecttype is a valid object type. The expression is True if objectname is of the object type specified by objecttype and False otherwise. statements are colon-separated statements to be executed if condition is True. elseifstatements are statements executed if the associated condition-n is True. elsestatements are statements executed if no previous condition (condition-n) expressions are True. |
On Error | On Error Resume Next Enables (or disables) an error-handling routine and specifies its location within a procedure. Causes execution to continue with the statement immediately following the statement that caused the runtime error, or with the statement immediately following the most recent call out of the procedure containing the On Error Resume Next statement. Execute an On Error Resume Next statement in each called routine if you want inline error handling within that routine. If you don't, any runtime error that occurs is fatal; an error message is displayed, and execution stops. |
Option Explicit | Option Explicit Used at script level to force explicit declaration of all variables (using Dim, Private, Public, or ReDim) within the script. If used, it must appear before any procedures within the script. |
Private | Private varname[([subscripts])][, varname[([subscripts])]]
. . . Used at script level to declare variables (and allocate storage) that are available only to the script in which they are declared. Variables referring to objects must be assigned an existing object using the Set statement before it can be used. Until it is assigned an object, the declared object variable has the special value Nothing. Using Private with empty parentheses causes declaration of a dynamic array. |
Public | Public varname[([subscripts])][, varname[([subscripts])]]
. . . Used at script level to declare variables (and allocate storage) that are available to all procedures in all scripts in all projects. Variables referring to objects must be assigned an existing object using the Set statement before it can be used. Until it is assigned an object, the declared object variable has the special value Nothing. Using Public with empty parentheses causes declaration of a dynamic array. |
Randomize | Randomize [number] Uses number to initialize (to seed) the Rnd function's random number generator. If no number is given, system timer is used. |
ReDim | ReDim [Preserve] varname(subscripts) [, varname(subscripts)]
. . . ReDim is used at the procedure level to declare dynamic-array variables and allocate or reallocate storage space--that is, to size or resize dynamic arrays that already have been declared formally using a Private, Public, or Dim without dimension subscripts. Note that making an array smaller than its original dimensions results in loss of data in the elements that are eliminated. Preserve is used to preserve data in an existing array when the size of the last array dimension is changed. If Preserve is used, only the last array dimension can be changed and the number of dimensions may not be changed at all. varname is the name of the variable. The subscripts argument uses the following syntax: upperbound [,upperbound] . . . Arrays of up to 60 dimensions can be declared. Array indexing starts at 0. Note that, when variables are initialized, numeric variables are initialized to 0 while string variables are initialized to zero-length strings (""). Variables referring to objects must be assigned an existing object using the Set statement before being used (until they are assigned an object, these variables have the value of Nothing). |
Rem | Rem comments or ` comments Used to include comments in your scripts. When Rem follows other statements on a line, it must be separated from the statements by a colon. |
Select Case | Select Case testexpression [Case expressionlist-n [statements-n]] . . . [Case Else expressionlist-n [elsestatements-n]] End Select Executes one of several groups of statements, depending on the value of an expression. If testexpression matches an expressionlist expression in more than one Case clause, only the statements following the first match are executed. Note that Select Case statements may be nested. testexpression is any numeric or string expression. expressionlist-n is a delimited list of expressions (required if Case is used). statements-n is a series of statements executed if testexpression matches any part of expressionlist-n. elsestatements-n is a series of statements executed if testexpression doesn't match any of the Case clauses. |
Set | Set objectvar = {objectexpression | Nothing} Assigns an object reference to a variable or property. Typically, Set creates a reference to an object (no copy of the object is created). Multiple variables can refer to the same object, and any change in the object is reflected in all variables that refer to it. objectvar the name of the variable or property. objectexpression is an expression consisting of the name of an object, another declared variable of the same object type, or a function or method that returns an object of the same object type. Nothing discontinues objectvar's association with the object and releases system and memory resources associated with the previously referenced object when no other variable refers to it. |
Sub | [Public | Private] Sub name [(arglist)] [statements] [Exit Sub] [statements] End Sub Declares the name, arguments, and code that form the body of a Sub procedure. Sub procedures are public by default (if not specified with Public or Private), and thus visible to all other procedures in your script. Sub procedures can't be contained inside another Function or Sub procedure. Unlike Function procedures, Sub procedures can't be used in expressions. Public indicates that the Sub procedure is accessible to all other procedures in all scripts. Private indicates that the Sub procedure is accessible only to other procedures in the script where it is declared. name is the Sub name. arglist is the list of variables (comma-separated) passed to the procedure. arglist has the syntax [ByVal | ByRef] varname[( )] where ByVal and ByRef indicate argument is passed by value and reference, respectively, and varname is the variable representing the argument. statements are statement groups to be executed. expression is the return value assigned to the function name. Exit Sub statements can appear anywhere in a Sub procedure and cause an immediate exit from a Sub procedure. Caution: Sub procedures can be called recursively. However, recursion can lead to stack overflow. A procedure can use a variable that is not explicitly declared in the procedure, but a naming conflict can occur if anything you have defined at the script level has the same name (use of Option Explicit is a good practice). |
While...Wend | While condition [statements] Wend Executes a series of statements as long as the condition is True. Nesting can occur to any level. condition is a numeric or string expression that evaluates to True or False (if Null, it is treated as False). |
VBScript provides a number of methods that can be used for manipulating objects
in your VBScript programs. Table C.7 provides a listing of all VBScript methods along
with brief descriptions of how each may be used.
Table C.7. VBScript methods.
VBScript Method | Syntax and Description |
Add | object.Add key, item Adds the specified key, item pair to the specified Dictionary object. If key exists, an error occurs. |
Clear | object.Clear Explicitly clears all property settings of the Err object after the error is handled (for example, when deferred error handling is used with On Error Resume Next). Clear is called automatically when the On Error Resume Next, Exit Sub, or Exit Function statements are executed. |
Close | object.Close Closes an open TextStream file specified by object. |
CreateTextFile | [object.]CreateTextFile(filename[, overwrite[, unicode]])
Creates a file (specified by filename) and returns a TextStream object
that can be used to read/write the file. If overwrite is True, the file
can be overwritten. If overwrite is False or omitted, existing files aren't
overwritten. If unicode is True, the file is created as a Unicode
file. If unicode is False or omitted, an ASCII file is created.
CreateTextFile can be used to open a text file, as in this example:
Set fs = CreateObject("Scripting.FileSystemObject") Set a = fs.CreateTextFile("d:\myfile.txt", True) a.WriteLine("This is only a test.") a.Close |
Exists | object.Exists(key) Returns a Boolean True if key exists in the specified Dictionary object; False otherwise. |
Items | object.Items Returns an array that contains all items in the specified Dictionary object. It can be used as in this example: Dim a, d, i `Create variables Set d = CreateObject("Scripting.Dictionary") d.Add "a", "Autobahn" `Add keys and items d.Add "b", "Beltway" d.Add "c", "Circle" a = d.Items `Get items For i = 0 To d.Count -1 `Iterate array Print a(i) `Print item Next ... |
Keys | object.Keys Returns an array that contains all keys in the specified Dictionary object. It can be used as in this example: Dim a, d, i `Create variables Set d = CreateObject("Scripting.Dictionary") d.Add "a", "Autobahn" `Add keys and items d.Add "b", "Beltway" d.Add "c", "Circle" a = d.Keys `Get keys For i = 0 To d.Count -1 `Iterate array Print a(i) `Print key Next ... |
OpenTextFile | [object.]OpenTextFile(filename[, iomode[, create[, format]]])
Opens a specified file and returns a TextStream object that can be used to read from or append to the file. object is optional and is the name of a FileSystemObject. filename is a required string expression that specifies the file to open. iomode is an optional constant (ForReading or ForAppending) that indicates how the file is opened. create is an optional Boolean value that specifies whether a new file can be created if filename does not exist. If True, new file is created. If omitted, no file created. format is an optional Tristate value that indicates the format of the opened file. If omitted, the file is opened as ASCII. Possible values are TristateTrue to open the file as Unicode, TristateFalse to open the file as ASCII, and TristateUseDefaultOpen to open the file using the system default. The following code snippet shows how to open a file for appending text: Dim fs, a Set fs = CreateObject("Scripting.FileSystemObject") Set a = fs.OpenTextFile("D:\mytestfile.txt", ÂForAppending, FALSE) ... a.Close |
Raise | object.Raise(number, source, description,
helpfile, helpcontext) Generates a runtime error. If Raise is used without specifying arguments, and the property settings of the Err object contain values that have not been cleared, those values become the values for your error. When setting the number property to your own error code in an Automation object, you add your error code number to the constant vbObjectError (to generate the error num- ber 1040, for example, assign vbObjectError + 1040 to the number property). All arguments are optional except number. object is the Err object. number is a Long integer identifying the nature of the error (VBScript errors, VBScript-defined and user-defined, are in the range 0-65535). source is a string expression that names the object or application that generated the error. If setting this property for an Automation object, use the form project.class. If nothing is specified, the programmatic ID of the current VBScript project is used. description is a string expression that describes the error (if not specified, the value in number is examined, and if it can be mapped to a runtime error code, a string provided by VBScript is used as description. If no VBScript error corresponds to number, a generic error message is used). helpfile is a fully qualified path to the Help file in which help on this error can be found (if unspecified, VBScript uses the fully qualified drive, path, and filename of the VBScript Help file). helpcontext is a context ID identifying a topic within helpfile that provides help for the error (if omitted, the VBScript Help file context ID for the error corresponding to the number property is used, if it exists). |
Read | object.Read(characters) Reads some number of characters (specified by characters) from a TextStream file specified by object and returns the resulting string. |
ReadAll | object.ReadAll Reads the entire TextStream file specified by object and returns the resulting string. For large files, it is recommended that reading is performed one line at a time to conserve memory resources. |
ReadLine | object.ReadLine Reads an entire line from the TextStream file specified by object and returns the resulting string. Note that the newline character is not read. |
Remove | object.Remove(key) Removes a key/item pair (for the specified key) from a Dictionary object specified by object. It can be used as in this example: Dim a, d, i `Create variables Set d = CreateObject("Scripting.Dictionary") d.Add "a", "Autobahn" `Add keys and items d.Add "b", "Beltway" d.Add "c", "Circle" ... a = d.Remove("b") `Remove second pair |
RemoveAll | object.RemoveAll Removes all key/item pairs from a Dictionary object specified by object. It can be used as in this example: Dim a, d, i `Create variables Set d = CreateObject("Scripting.Dictionary") d.Add "a", "Autobahn" `Add keys and items d.Add "b", "Beltway" d.Add "c", "Circle" ... a = d.RemoveAll("b") `Clear dictionary |
Skip | object.Skip(characters) Used to skip some number of characters (specified by characters) when reading the TextStream file specified by object. |
SkipLine | object.SkipLine Skips the next line when reading the TextStream file specified by object. |
Write | object.Write(string) Writes the specified string to the TextStream file specified by object. No intervening spaces or characters are written between strings. |
WriteBlankLines | object.WriteBlankLines(lines) Writes a number of newline characters (specified by lines) to the TextStream file specified by object. |
WriteLine | object.WriteLine([string)] Writes the specified string (and a newline character) to the TextStream file specified by object. If no string is specified, a newline is written to the file. |
VBScript provides objects for handling dictionaries (arrays of key/value pairs),
errors, and file I/O. Table C.8 provides a listing of all VBScript objects along
with brief descriptions of how each may be used.
Table C.8. VBScript objects.
VBScript Object | Syntax and Description |
Dictionary | Scripting.Dictionary Stores data key and item pairs. It is equivalent to an associative array in the Perl scripting language. Items can be any form of data. Keys are used to retrieve individual items and can be anything but an array (they are typically integers or strings). Create a Dictionary object and make these additions: Dim d Set d = CreateObject("Scripting.Dictionary") d.Add "a", "Autobahn" ... |
Err | Err[.{property | method}] Err is an intrinsic object with global scope and does not need to be created explicitly in your code. Properties of this object are set by the generator of an error (Visual Basic, an Automation object, or the VBScript programmer). The default property is Number.Err.Number (which contains an integer and can be used by an Automation object to return an SCODE). Properties of the Err object are filled with information about a runtime error. The Raise method can be used to generate runtime errors in your code. Err properties are reset to 0 or "" following an On Error Resume Next statement and after a Sub or Exit Function statement within an error-handling routine. Additionally, the Clear method can be used to explicitly reset Err. |
FileSystemObject | Scripting.FileSystemObject Provides access to a computer's file system. It provide two methods: one to create a file and one to open a text file. A FileSystemObject can be created and used like this: Set fs CreateObject("Scripting.FileSystemObject") Set a = fs.CreateTextFile("D:\myfile.txt", True) a.WriteLine("This is just a test.") a.Close The CreateObject function returns FileSystemObject (fs). The CreateTextFile method creates the file as a TextStream object (a). The WriteLine method writes a line of text to the created text file. The Close method flushes the buffer and closes the file. |
TextStream | TextStream.{property | method} Facilitates sequential access to a file. property and method can be any of those associated with the TextStream object. See FileSystemObject for sample use. |
All VBScript objects have a number of properties that can be in your VBScript
programs for performing conditional execution of statements, setting the context
of Help, deterring information about dictionary objects, and so on. Table C.9 provides
a listing of all VBScript properties with a brief description of how each may be
used.
Table C.9. VBScript properties.
VBScript Property | Syntax and Description |
AtEndOfLine | object.AtEndOfLine Returns True if the file pointer is at the end of a TextStream file; returns False otherwise. Applies only to TextStream files opened for reading (an error occurs otherwise). This property can be used as in this example: Dim fs, a, retstring Set fs = CreateObject("Scripting.FileSystemObject") Set a = fs.OpenTextFile("d:\myfile.txt", ForReading, False) Do While a.AtEndOfLine <> True retstring = a.Read(1) ... Loop a.Close |
AtEndOfStream | object.AtEndOfStream Returns True if the file pointer is at the end of a TextStream file; returns False otherwise. Applies only to TextStream files opened for reading (an error occurs otherwise). This property can be used as in this example: Dim fs, a, retstring Set fs = CreateObject("Scripting.FileSystemObject") Set a = fs.OpenTextFile("d:\myfile.txt", ForReading, False) Do While a.AtEndOfStream <> True retstring = a.Read(1) ... Loop a.Close |
Column | object.Column A read-only property that returns the column number of the current character position in a TextStream file. |
CompareMode | object.CompareMode[ = compare] Sets and returns the comparison mode for comparing string keys in a Dictionary object. It uses the same values as the compare argument for the StrComp function. Acceptable values are 0 (Binary), 1 (Text), and 2 (Database). Values greater than 2 can be used to refer to comparisons using specific locale IDs (LCIDs). Attempting to change the comparison mode of a Dictionary object that contains data causes an error. |
Count | object.Count A read-only property that returns the number of items in a Dictionary object. It can be used as in this example: Dim a, d, I Set d = CreateObject("Scripting.Dictionary") d.Add "a", "Autobahn" `Add some keys and items. d.Add "b", "Beltway" d.Add "c", "Circle" a = d.Keys `Get the keys For i = 0 To d.Count -1 `Iterate through array Print a(i) `Print key Next ... |
Description | object.Description [= stringexpression] Returns or sets a descriptive string associated with an error. It can be used to alert users of error conditions that the program doesn't handle. If Description isn't filled in, and the value of Number (see entry later in this table) corresponds to a VBScript runtime error, the descriptive string associated with that error is returned. object is the Err object. stringexpression contains a description of the error. |
HelpContext | object.HelpContext [= contextID] Sets or returns a context ID for a topic in a Help file. If a Help file is specified in HelpFile (see next entry), the HelpContext property is used to automatically display the topic identified. If both HelpFile and HelpContext are empty, the value of Number (see later entry) is checked, and, if it corresponds to a VBScript runtime error value, the VBScript Help context ID for that error is used. If the Number value doesn't correspond to a VBScript error, the contents screen for the VBScript Help file is displayed. object is the Err object. contextID is a valid identifier for a topic in the Help file (it is optional). |
HelpFile | object.HelpFile [= contextID] Sets or returns a fully qualified path to the Help file. If a Help file is specified in HelpFile, it is invoked automatically if a user clicks the Help button in the error message dialog box (or presses the F1 key). If the HelpContext property contains a valid context ID for the specified file, that topic is displayed automatically. If no HelpFile is specified, the VBScript Help file is displayed. object is the Err object. contextID is a fully qualified path to the Help file (it is optional). |
Item | object.Item(key)[ = newitem] Sets or returns an item for the specified key in a Dictionary object. If key is not found when changing an item, a new key is created with the specified newitem. If key is not found when attempting to retrieve an existing item, a new key is created, and its corresponding item is left empty. object is the name of the Dictionary (it is required). key associated with the items to be retrieved or added (it is required). newitem is the new value associated with key (it is optional). |
Line | object.Line A read-only property that returns the current line number in a TextStream file. Line is 1 when the file is first opened (prior to writing anything). object is always the name of a TextStream object. |
Number | object.Number [= errornumber] Returns or sets a numeric value specifying an error. Number is the Err object's default property. object is the Err object. errornumber is an integer that represents a VBScript error number or an SCODE error value. If returning a user-defined error from an Automation object, set Err.Number by adding the number you selected as an error code to the constant vbObjectError, as shown in the following code snippet: Err.Raise Number:= vbObjectError + 2040, Source:= "MyClass" Source object.Source [= stringexpression] object is the Err object. stringexpression represents the application generating the error. This property returns or sets the name of the object or application that originally generated the error. The Source property specifies a string expression that is usually the class name or programmatic ID of the object that caused the error. Source is used to provide your users with information when your code is unable to handle an error generated in an accessed object. When generating an error from code, Source is your application's programmatic ID. |