- C -

VBScript Language Reference

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/



A Summary of VBScript Features

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

Differences Between VBA and VBScript

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 Constants

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 Operators

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:
exp1 Imp exp2 = result
True True True
True False False
True Null Null
False True True
False False True
False Null True
Null True True
Null False Null
Null Null Null
\ 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.

VBScript Functions

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:

expression is CStr returns
Boolean String containing True or False
Date A string containing date in your system's
short format
Null A runtime error
Empty "" (a zero-length string)
Error A string containing the word Error followed by error number
Other numeric A string containing the number
Use CStr (rather than Str) to provide internationally aware conversions from any other data type to a String subtype (different decimals are recognized properly depending on the locale setting of your system).
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:

yyyy Year
q Quarter
m Month
y Day of year
d Day
w Weekday
ww Week of year
h Hour
m Minute
s Second


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:

vbUseSystem 0 Use National Language Support (NLS) API setting
vbSunday 1 Sunday (default)
vbMonday 2 Monday
vbTuesday 3 Tuesday
vbWednesday 4 Wednesday
vbThursday 5 Thursday
vbFriday 6 Friday
vbSaturday 7 Saturday


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:

vbUseSystem 0 Use National Language Support (NLS) API setting
vbFirstJan1 1 Start with the week in which January 1 occurs (default)
vbFirstFourDays 2 Start with week having at least four days in the new year
vbFirstFullWeek 3 Start with the first full week of the new year


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:

vbBinaryCompare 0 Perform a binary comparison
vbTextCompare 1 Perform a textual comparison
VbDatabaseCompare 2 Perform a comparison based on infor-mation contained in the database where the comparison is to be performed
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:

TristateTrue -1 True
TristateFalse 0 False
TristateUseDefault -2 Use the setting from the computer's regional settings.


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:

vbGeneralDate 0 Displays a date and/or time. If there is a date part, display it as a short date. If there is a time part, display it as a long time. If present, both parts are displayed.
vbLongDate 1 Displays a date using the long date format specified in your computer's regional settings.
vbShortDate 2 Displays a date using the short date format specified in your computer's regional settings.
vbLongTime 3 Displays a time using the time format specified in your computer's regional settings.
vbShortTime 4 Displays a time using the 24-hour format (hh:mm).
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:

vbBinaryCompare 0 Binary comparison
vbTextCompare 1 Textual comparison
vbDatabaseCompare 2 Comparison based on information contained in the database where the comparison is performed

Following are InStr return values:

Condition Return Value
string1 is 0 length 0
string1 is Null Null
string2 is 0 length start
string2 is Null Null
string2 is not found 0
string2 is found Position where match was found
start > length of string2 0


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:

Constant Value Description
vbOKOnly 0 Displays OK button only
vbOKCancel 1 Displays OK and Cancel buttons
vbAbortRetryIgnore 2 Displays Abort, Retry, and Ignore buttons
vbYesNoCancel 3 Displays Yes, No, and Cancel buttons
vbYesNo 4 Displays Yes and No buttons
vbRetryCancel 5 Displays Retry and Cancel buttons
vbCritical 16 Displays Critical Message icon
vbQuestion 32 Displays Warning Query icon
vbExclamation 48 Displays Warning Message icon
vbInformation 64 Displays Information Message icon
vbDefaultButton1 0 First button is default
vbDefaultButton2 256 Second button is default
vbDefaultButton3 512 Third button is default
vbDefaultButton4 768 Fourth button is default
vbApplicationModal 0 Application modal; requires the user to respond to the dialog box before continuing in the current application
VbSystemModal 4096 System modal; all applications are suspended until the user responds to the dialog box

Following are MsgBox return values indicating which button was clicked:
Constant Value Button
vbOK 1 OK
vbCancel 2 Cancel
vbAbort 3 Abort
vbRetry 4 Retry
vbIgnore 5 Ignore
vbYes 6 Yes
vbNo 7 No
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:

vbBinaryCompare 0 Binary comparison
vbTextCompare 1 Textual comparison
vbDatabaseCompare 2 Comparison based on information contained in the database where the comparison is performed


Following are Replace return values:

Condition Return Value
expression is 0 length Zero-length string
expression is Null An error
find is 0 length Copy of expression
replacewith is 0 length Copy of expression with all occurrences of find removed
start > Len(expression) Zero-length string
count is 0 Copy of expression
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:

number < 0 Rnd returns the same number every time, using number as the seed.
number > 0 Rnd returns the next random number in the sequence.
number = 0 Rnd returns the most recently generated number.
no number Rnd returns the next random number in the sequence.


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:
vbBinaryCompare 0 Binary comparison
vbTextCompare 1 Textual comparison
vbDatabaseCompare 2 Comparison based on information contained in the database where the comparison is performed
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:

Condition Return Value
string1 less than string2 -1
string1 equal to string2 0
string1 greater than string2 1
string1 or string2 is Null Null
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:

Constant Value
vbEmpty 0 (uninitialized)
vbNull 1
vbInteger 2
vbLong 3
vbSingle 4
vbDouble 5
vbCurrency 6
vbDate 7
vbString 8
vbObject 9 (Automation object)
vbError 10
vbBoolean 11
vbVariant 12 (used only with arrays of Variants)
vbDataObject 13 (data-access object)
vbByte 17
vbArray 8192
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:

Constant Value
vbUseSystem 0 (use NLS API setting)
vbSunday 1
vbMonday 2
vbTuesday 3
vbWednesday 4
vbThursday 5
vbFriday 6
vbSaturday 7


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 Statements

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