Documentation
Documentation
Information
VBScript Features
VBA Features not in VBScript
VBScript Features not in VBA
Microsoft Scripting Run-Time Features
Microsoft® Visual Basic® Scripting Edition
Keyword List
Abs Function
Addition Operator (+)
And Operator
Array Function
Asc Function
Assignment Operator (=)
Atn Function
Call Statement
CBool Function
CByte Function
CCur Function
CDate Function
CDbl Function
Chr Function
CInt Function
Class Object
Class Statement
Clear Method
CLng Function
Color Constants
Comparison Constants
Concatenation Operator (&)
Const Statement
Cos Function
CreateObject Function
CSng Function
CStr Function
Date and Time Constants
Date Format Constants
Date Function
DateAdd Function
DateDiff Function
DatePart Function
DateSerial Function
DateValue Function
Day Function
Description Property
Dictionary Object
Dim Statement
Division Operator (/)
Do...Loop Statement
Empty
Eqv Operator
Erase Statement
Err Object
Eval Function
Execute Method
Execute Statement
Exit Statement
Exp Function
Exponentiation Operator (^)
False
FileSystemObject Object
Filter Function
FirstIndex Property
Fix Function
For...Next Statement
For Each...Next Statement
FormatCurrency Function
FormatDateTime Function
FormatNumber Function
FormatPercent Function
Function Statement
GetObject Function
GetRef Function
Global Property
Hex Function
HelpContext Property
HelpFile Property
Hour Function
If...Then...Else Statement
IgnoreCase Property
Imp Operator
Initialize Event
InputBox Function
InStr Function
InStrRev Function
Int Function
Integer Division Operator (\)
Is Operator
IsArray Function
IsDate Function
IsEmpty Function
IsNull Function
IsNumeric Function
IsObject Function
Join Function
LBound Function
LCase Function
Left Function
Len Function
Length Property
LoadPicture Function
Log Function
LTrim Function
Match Object
Matches Collection
Mid Function
Minute Function
Miscellaneous Constants
Mod Operator
Month Function
MonthName Function
MsgBox Constants
MsgBox Function
Multiplication Operator (*)
Negation Operator (-)
Not Operator
Now Function
Nothing
Null
Number Property
Oct Function
On Error Statement
Operator Precedence
Option Explicit Statement
Or Operator
Pattern Property
Private Statement
PropertyGet Statement
PropertyLet Statement
PropertySet Statement
Public Statement
Raise Method
Randomize Statement
ReDim Statement
RegExp Object
Rem Statement
Replace Function
Replace Method
RGB Function
Right Function
Rnd Function
Round Function
RTrim Function
ScriptEngine Function
ScriptEngineBuildVersion Function
ScriptEngineMajorVersion Function
ScriptEngineMinorVersion Function
Second Function
Select Case Statement
Set Statement
Sgn Function
Sin Function
Source Property
Space Function
Split Function
Sqr Function
StrComp Function
String Constants
String Function
StrReverse Function
Sub Statement
Subtraction Operator (-)
Tan Function
Terminate Event
Test Method
Time Function
Timer Function
TimeSerial Function
TimeValue Function
Trim Function
Tristate Constants
True
TypeName Function
UBound Function
UCase Function
Value Property
VarType Constants
VarType Function
VBScript Constants
Weekday Function
WeekdayName Function
While...Wend Statement
With Statement
Xor Operator
Year Function
Microsoft® Visual Basic® Scripting Edition VBScript Language Reference
Version Information
Constants
Color Constants
Comparison Constants
Date and Time Constants
Date Format Constants
Miscellaneous Constants
MsgBox Constants
String Constants
Tristate Constants
VarType Constants
VBScript Constants
Microsoft® Visual Basic® Scripting Edition VBScript Language Reference
Version Information
VBScript Errors
Run-time Errors
Syntax Errors
Microsoft® Visual Basic® Scripting Edition VBScript Language Reference
Version Information
Events
Initialize Event
Terminate Event
Microsoft® Visual Basic® Scripting
VBScript Language Reference
Edition Functions Version Information
Abs Function
Array Function
Asc Function
Atn Function
CBool Function
CByte Function
CCur Function
CDate Function
CDbl Function
Chr Function
CInt Function
CLng Function
Cos Function
CreateObject Function
CSng Function
CStr Function
Date Function
DateAdd Function
DateDiff Function
DatePart Function
DateSerial Function
DateValue Function
Day Function
Eval Function
Exp Function
Filter Function
Fix Function
FormatCurrency Function
FormatDateTime Function
FormatNumber Function
FormatPercent Function
GetObject Function
GetRef Function
Hex Function
Hour Function
InputBox Function
InStr Function
InStrRev Function
Int Function
IsArray Function
IsDate Function
IsEmpty Function
IsNull Function
IsNumeric Function
IsObject Function
Join Function
LBound Function
LCase Function
Left Function
Len Function
LoadPicture Function
Log Function
LTrim Function
Mid Function
Minute Function
Month Function
MonthName Function
MsgBox Function
Now Function
Oct Function
Replace Function
RGB Function
Right Function
Rnd Function
Round Function
RTrim Function
ScriptEngine Function
ScriptEngineBuildVersion Function
ScriptEngineMajorVersion Function
ScriptEngineMinorVersion Function
Second Function
Sgn Function
Sin Function
Space Function
Split Function
Sqr Function
StrComp Function
String Function
StrReverse Function
Tan Function
Time Function
Timer Function
TimeSerial Function
TimeValue Function
Trim Function
TypeName Function
UBound Function
UCase Function
VarType Function
Weekday Function
WeekdayName Function
Year Function
Microsoft® Visual Basic® Scripting Edition VBScript Language Reference
Version Information
Methods
Clear Method
Execute Method
Raise Method
Replace Method
Test Method
Microsoft® Visual Basic® Scripting Edition VBScript Language Reference
Version Information
Objects
Class Object
Dictionary Object
Err Object
FileSystemObject Object
Match Object
Matches Collection
RegExp Object
Microsoft® Visual Basic® Scripting Edition VBScript Language Reference
Version Information
Operators
Addition Operator (+)
And Operator
Assignment Operator (=)
Concatenation Operator (&)
Division Operator (/)
Eqv Operator
Exponentiation Operator (^)
Imp Operator
Integer Division Operator (\)
Is Operator
Mod Operator
Multiplication Operator (*)
Negation Operator (-)
Not Operator
Operator Precedence
Or Operator
Subtraction Operator (-)
Xor Operator
Microsoft® Visual Basic® Scripting Edition VBScript Language Reference
Version Information
Properties
Description Property
FirstIndex Property
Global Property
HelpContext Property
HelpFile Property
IgnoreCase Property
Length Property
Number Property
Pattern Property
Source Property
Value Property
Microsoft® Visual Basic® Scripting
VBScript Language Reference
Edition Statements Version Information
Call Statement
Class Statement
Const Statement
Dim Statement
Do...Loop Statement
Erase Statement
Execute Statement
Exit Statement
For...Next Statement
For Each...Next Statement
Function Statement
If...Then...Else Statement
On Error Statement
Option Explicit Statement
Private Statement
Property Get Statement
Property Let Statement
Property Set Statement
Public Statement
Randomize Statement
ReDim Statement
Rem Statement
Select Case Statement
Set Statement
Sub Statement
While...Wend Statement
With Statement
Using
Microsoft® Visual Basic® Scripting Edition
VBScript Tutorial
Previous
Conditional Next
Statements
Controlling Program Execution
You can control the flow of your script with conditional statements and
looping statements. Using conditional statements, you can write VBScript
code that makes decisions and repeats actions. The following conditional
statements are available in VBScript:
If...Then...Else statement
Select Case statement
To run only one statement when a condition is True, use the single-line
syntax for the If...Then...Else statement. The following example shows the
single-line syntax. Notice that this example omits the Else keyword.
Sub FixDate()
Dim myDate
myDate = #2/13/95#
If myDate < Now Then myDate = Now
End Sub
To run more than one line of code, you must use the multiple-line (or block)
syntax. This syntax includes the End If statement, as shown in the
following example:
Sub AlertUser(value)
If value = 0 Then
AlertLabel.ForeColor = vbRed
AlertLabel.Font.Bold = True
AlertLabel.Font.Italic = True
End If
End Sub
Running Certain Statements if a Condition is True and Running Others if a Condition is
False
Sub AlertUser(value)
If value = 0 Then
AlertLabel.ForeColor = vbRed
AlertLabel.Font.Bold = True
AlertLabel.Font.Italic = True
Else
AlertLabel.Forecolor = vbBlack
AlertLabel.Font.Bold = False
AlertLabel.Font.Italic = False
End If
End Sub
Deciding Between Several Alternatives
Sub ReportValue(value)
If value = 0 Then
MsgBox value
ElseIf value = 1 Then
MsgBox value
ElseIf value = 2 then
Msgbox value
Else
Msgbox "Value out of range!"
End If
You can add as many ElseIf clauses as you need to provide alternative
choices. Extensive use of the ElseIf clauses often becomes cumbersome. A
better way to choose between several alternatives is the Select Case
statement.
Making Decisions with Select Case
A Select Case structure works with a single test expression that is evaluated
once, at the top of the structure. The result of the expression is then
compared with the values for each Case in the structure. If there is a match,
the block of statements associated with that Case is executed:
Using Do Loops
Sub ChkFirstWhile()
Dim counter, myNum
counter = 0
myNum = 20
Do While myNum > 10
myNum = myNum - 1
counter = counter + 1
Loop
MsgBox "The loop made " & counter & " repetitions."
End Sub
Sub ChkLastWhile()
Dim counter, myNum
counter = 0
myNum = 9
Do
myNum = myNum - 1
counter = counter + 1
Loop While myNum > 10
MsgBox "The loop made " & counter & " repetitions."
End Sub
Repeating a Statement Until a Condition Becomes True
You can use the Until keyword in two ways to check a condition in a
Do...Loop statement. You can check the condition before you enter the loop
(as shown in the following ChkFirstUntil example), or you can check it
after the loop has run at least once (as shown in the ChkLastUntil example).
As long as the condition is False, the looping occurs.
Sub ChkFirstUntil()
Dim counter, myNum
counter = 0
myNum = 20
Do Until myNum = 10
myNum = myNum - 1
counter = counter + 1
Loop
MsgBox "The loop made " & counter & " repetitions."
End Sub
Sub ChkLastUntil()
Dim counter, myNum
counter = 0
myNum = 1
Do
myNum = myNum + 1
counter = counter + 1
Loop Until myNum = 10
MsgBox "The loop made " & counter & " repetitions."
End Sub
Exiting a Do...Loop Statement from Inside the Loop
You can exit a Do...Loop by using the Exit Do statement. Because you
usually want to exit only in certain situations, such as to avoid an endless
loop, you should use the Exit Do statement in the True statement block of
an If...Then...Else statement. If the condition is False, the loop runs as
usual.
In the following example, myNum is assigned a value that creates an endless loop. The
If...Then...Else statement checks for this condition, preventing the endless repetition.
Sub ExitExample()
Dim counter, myNum
counter = 0
myNum = 9
Do Until myNum = 10
myNum = myNum - 1
counter = counter + 1
If myNum < 10 Then Exit Do
Loop
MsgBox "The loop made " & counter & " repetitions."
End Sub
Using While...Wend
Using For...Next
Sub DoMyProc50Times()
Dim x
For x = 1 To 50
MyProc
Next
End Sub
Using the Step keyword, you can increase or decrease the counter variable
by the value you specify. In the following example, the counter variable j is
incremented by 2 each time the loop repeats. When the loop is finished,
total is the sum of 2, 4, 6, 8, and 10.
Sub TwosTotal()
Dim j, total
For j = 2 To 10 Step 2
total = total + j
Next
MsgBox "The total is " & total
End Sub
To decrease the counter variable, you use a negative Step value. You must
specify an end value that is less than the start value. In the following
example, the counter variable myNum is decreased by 2 each time the loop
repeats. When the loop is finished, total is the sum of 16, 14, 12, 10, 8, 6, 4,
and 2.
Sub NewTotal()
Dim myNum, total
For myNum = 16 To 2 Step -2
total = total + myNum
Next
MsgBox "The total is " & total
End Sub
You can exit any For...Next statement before the counter reaches its end
value by using the Exit For statement. Because you usually want to exit
only in certain situations, such as when an error occurs, you should use the
Exit For statement in the True statement block of an If...Then...Else
statement. If the condition is False, the loop runs as usual.
For Each I in d
Document.frmForm.Elements(I).Value = D.Item(I)
Next
End Sub
-->
</SCRIPT>
<BODY>
<CENTER>
<FORM NAME="frmForm"
VBScript Tutorial
VBScript and Previous
Next
Forms
Simple Validation
You can use Visual Basic Scripting Edition to do much of the form
processing that you'd usually have to do on a server. You can also do things
that just can't be done on the server.
Here's an example of simple client-side validation. The HTML code is for a text box and a button. If
you use Microsoft® Internet Explorer to view the page produced by the following code, you'll see a
small text box with a button next to it.
<HTML>
<HEAD><TITLE>Simple Validation</TITLE>
<SCRIPT LANGUAGE="VBScript">
<!--
Sub Button1_OnClick
Dim TheForm
Set TheForm = Document.ValidForm
If IsNumeric(TheForm.Text1.Value) Then
If TheForm.Text1.Value < 1 Or TheForm.Text1.Value > 1
MsgBox "Please enter a number between 1 and 10."
Else
MsgBox "Thank you."
End If
Else
MsgBox "Please enter a numeric value."
End If
End Sub
-->
</SCRIPT>
</HEAD>
<BODY>
<H3>Simple Validation</H3><HR>
<FORM NAME="ValidForm">
Enter a value between 1 and 10:
<INPUT NAME="Text1" TYPE="TEXT" SIZE="2">
<INPUT NAME="Button1" TYPE="BUTTON" VALUE="
</FORM>
</BODY>
</HTML>
The difference between this text box and the examples on A Simple
VBScript Page is that the Value property of the text box is used to check
the entered value. To get the Value property, the code has to qualify the
reference to the name of the text box.
You can always write out the full reference Document.ValidForm.Text1. However, where you have
multiple references to form controls, you'll want to do what was done here. First declare a variable.
Then use the Set statement to assign the form to the variable TheForm. A regular assignment
statement, such as Dim, doesn't work here; you must use Set to preserve the reference to an object.
Notice that the example directly tests the value against a number: it uses the
IsNumeric function to make sure the string in the text box is a number.
Although VBScript automatically converts strings and numbers, it's always
a good practice to test a user-entered value for its data subtype and to use
conversion functions as necessary. When doing addition with text box
values, convert the values explicitly to numbers because the plus sign (+)
operator represents both addition and string concatenation. For example, if
Text1 contains "1" and Text2 contains "2", you see the following results:
<SCRIPT LANGUAGE="VBScript">
<!--
Sub Button1_OnClick
Dim TheForm
Set TheForm = Document.ValidForm
If IsNumeric(TheForm.Text1.Value) Then
If TheForm.Text1.Value < 1 Or TheForm.Text1.Value > 10 Then
MsgBox "Please enter a number between 1 and 10."
Else
MsgBox "Thank you."
TheForm.Submit ' Data correct; send to server.
End If
Else
MsgBox "Please enter a numeric value."
End If
End Sub
-->
</SCRIPT>
To send the data to the server, the code invokes the Submit method on the
form object when the data is correct. From there, the server handles the data
just as it otherwise would—except that the data is correct before it gets
there. Find complete information about the Submit method and other
methods in the Internet Explorer Scripting Object Model documentation,
which can be found on the Microsoft® Web site
(http://www.microsoft.com).
So far, you've seen only the standard HTML <FORM> objects. Internet Explorer also lets you exploit
the full power of ActiveX® controls (formerly called OLE controls) and Java™ objects.
tags"> tags">
Using
Microsoft® Visual Basic® Scripting Edition
VBScript Tutorial
VBScript with Previous
Objects
Using Objects
<OBJECT
classid="clsid:99B42120-6EC7-11CF-A6C7-00AA00A
id=lblActiveLbl
width=250
height=250
align=left
hspace=20
vspace=0
>
<PARAM NAME="Angle" VALUE="90">
<PARAM NAME="Alignment" VALUE="4">
<PARAM NAME="BackStyle" VALUE="0">
<PARAM NAME="Caption" VALUE="A Simple Desultor
<PARAM NAME="FontName" VALUE="Verdana, Arial, H
<PARAM NAME="FontSize" VALUE="20">
<PARAM NAME="FontBold" VALUE="1">
<PARAM NAME="FrColor" VALUE="0">
</OBJECT>
You can get properties, set properties, and invoke methods just as with any
of the form controls. The following code, for example, includes <FORM>
controls you can use to manipulate two properties of the Label control:
<FORM NAME="LabelControls">
<INPUT TYPE="TEXT" NAME="txtNewText" SIZE=25>
<INPUT TYPE="BUTTON" NAME="cmdChangeIt" VAL
<INPUT TYPE="BUTTON" NAME="cmdRotate" VALUE
</FORM>
With the form defined, an event procedure for the cmdChangeIt button
changes the label text:
<SCRIPT LANGUAGE="VBScript">
<!--
Sub cmdChangeIt_onClick
Dim TheForm
Set TheForm = Document.LabelControls
lblActiveLbl.Caption = TheForm.txtNewText.Value
End Sub
-->
</SCRIPT>
The code qualifies references to controls and values inside the forms just as
in the Simple Validation example.
Several ActiveX controls are available for use with Internet Explorer. You can find complete
information about the properties, methods, and events there, as well as the class identifiers (CLSID)
for the controls on the Microsoft® Web site (http://www.microsoft.com). You can find more
information about the <OBJECT> tag on the Internet Explorer 4.0 Author's Guide and HTML
Reference page.
Reference
DriveType Constants
File Attribute Constants
File Input/Output Constants
FileSystemObject Constants
SpecialFolder Constants
Microsoft® Visual Basic® Scripting Edition Scripting Run-Time Library
Reference
Methods Version Information
Dictionary Object
Drive Object
Drives Collection
File Object
Files Collection
FileSystemObject Object
Folder Object
Folders Collection
TextStream Object
Microsoft® Visual Basic® Scripting Edition Scripting Run-Time Library
Reference
Properties Version Information
AtEndOfLine Property
AtEndOfStream Property
Attributes Property
AvailableSpace Property
Column Property
CompareMode Property
Count Property
DateCreated Property
DateLastAccessed Property
DateLastModified Property
Drive Property
DriveLetter Property
Drives Property
DriveType Property
Files Property
FileSystem Property
FreeSpace Property
IsReady Property
IsRootFolder Property
Item Property
Key Property
Line Property
Name Property
ParentFolder Property
Path Property
RootFolder Property
SerialNumber Property
ShareName Property
ShortName Property
ShortPath Property
Size Property
SubFolders Property
TotalSize Property
Type Property
VolumeName Property
The
Microsoft® Scripting Library - FileSystemObject
Next
FileSystemObject
Object Model
When writing scripts for Active Server Pages, the Windows Scripting Host,
or other applications where scripting can be used, it's often important to
add, move, change, create, or delete folders (directories) and files on the
Web server. It may also be necessary to get information about and
manipulate drives attached to the Web server.
Scripting allows you to process drives, folders, and files using the
FileSystemObject (FSO) object model, which is explained in the following
sections:
Introduction to the
FileSystemObject
and the Previous
Next
Scripting Run-
Time Library
Reference
The FileSystemObject (FSO) object model allows you to use the familiar
object.method syntax with a rich set of properties, methods, and events to
process folders and files.
Use this object-based tool with:
Because use of the FSO on the client side raises serious security issues about
providing potentially unwelcome access to a client's local file system, this
documentation assumes use of the FSO object model to create scripts executed
by Internet Web pages on the server side. Since the server side is used, the
Internet Explorer default security settings do not allow client-side use of the
FileSystemObject object. Overriding those defaults could subject a local
computer to unwelcome access to the file system, which could result in total
destruction of the file system's integrity, causing loss of data, or worse.
The FSO object model gives your server-side applications the ability to create, alter, move, and delete
folders, or to detect if particular folders exist, and if so, where. You can also find out information about
folders, such as their names, the date they were created or last modified, and so forth.
The FSO object model also makes it easy to process files. When processing files, the primary goal is to
store data in a space- and resource-efficient, easy-to-access format. You need to be able to create files, insert
and change the data, and output (read) the data. Since storing data in a database, such as Access or SQL
Server, adds a significant amount of overhead to your application, storing your data in a binary or text file
may be the most efficient solution. You may prefer not to have this overhead, or your data access
requirements may not require all the extra features associated with a full-featured database.
The FSO object model, which is contained in the Scripting type library (Scrrun.dll), supports text file
creation and manipulation through the TextStream object. Although it does not yet support the creation or
manipulation of binary files, future support of binary files is planned.
Microsoft® Scripting Library - FileSystemObject
FileSystemObject Previous
Next
Objects
The FileSystemObject (FSO) object model contains the following objects
and collections.
Object/Collection Description
Main object. Contains methods and
properties that allow you to create, delete,
gain information about, and generally
FileSystemObject manipulate drives, folders, and files. Many
of the methods associated with this object
duplicate those in other FSO objects; they
are provided for convenience.
Object. Contains methods and properties that
allow you to gather information about a
drive attached to the system, such as its share
name and how much room is available. Note
that a "drive" isn't necessarily a hard disk,
Drive
but can be a CD-ROM drive, a RAM disk,
and so forth. A drive doesn't need to be
physically attached to the system; it can be
also be logically connected through a
network.
Collection. Provides a list of the drives
attached to the system, either physically or
logically. The Drives collection includes all
Drives
drives, regardless of type. Removable-media
drives need not have media inserted for them
to appear in this collection.
Object. Contains methods and properties that
allow you to create, delete, or move a file.
File
Also allows you to query the system for a
file name, path, and various other properties.
Collection. Provides a list of all files
Files
contained within a folder.
Object. Contains methods and properties that
allow you to create, delete, or move folders.
Folder Also allows you to query the system for
folder names, paths, and various other
properties.
Collection. Provides a list of all the folders
Folders
within a Folder.
Object. Allows you to read and write text
TextStream
files.
Microsoft® Scripting Library - FileSystemObject
The FSO object model is contained in the Scripting type library, which is
located in the Scrrun.dll file. Therefore, you must have Scrrun.dll in the
appropriate system directory on your Web server to use the FSO object
model.
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
This sample code demonstrates how to create an instance of the
FileSystemObject.
In JScript, use this code to do the same thing:
var fso;
fso = new ActiveXObject("Scripting.FileSystemObject");
In both of these examples, Scripting is the name of the type library and
FileSystemObject is the name of the object that you want to create. You
can create only one instance of the FileSystemObject object, regardless of
how many times you try to create another.
To gain access to an existing drive, file, or folder, use the appropriate "get"
method of the FileSystemObject object:
GetDrive
GetFolder
GetFile
Dim fso, f1
Set fso = CreateObject("Scripting.FileSystemObject")
Set f1 = fso.GetFile("c:\test.txt")
To do the same thing in JScript, use the following code:
Sub CreateFolder
Dim fso, fldr
Set fso = CreateObject("Scripting.FileSystemObject")
Set fldr = fso.CreateFolder("C:\MyTest")
Response.Write "Created folder: " & fldr.Name
End Sub
To set a variable to the CreateFolder function in JScript, use this syntax:
function CreateFolder()
{
var fso, fldr;
fso = new ActiveXObject("Scripting.FileSystemObject");
fldr = fso.CreateFolder("C:\\MyTest");
Response.Write("Created folder: " + fldr.Name);
}
Accessing the Object's Properties
Once you have a handle to an object, you can access its properties. For
example, to get the name of a particular folder, first create an instance of the
object, then get a handle to it with the appropriate method (in this case, the
GetFolder method, since the folder already exists).
Use this code to get a handle to the GetFolder method in VBScript:
Dim fso, f1
Set fso = CreateObject("Scripting.FileSystemObject")
' Get a File object to query.
Set f1 = fso.GetFile("c:\detlog.txt")
' Print information.
Response.Write "File last modified: " & f1.DateLastModified
To find out the same thing in JScript, use this code:
The Drive object allows you to gain information about the various drives
attached to a system, either physically or over a network. Its properties
allow you to obtain information about:
View the sample code to see how these properties are used in
FileSystemObject.
Use the Drive object to gather information about a drive. You won't see a
reference to an actual Drive object in the following code; instead, use the
GetDrive method to get a reference to an existing Drive object (in this
case, drv).
The following example demonstrates how to use the Drive object in VBScript:
Sub ShowDriveInfo(drvPath)
Dim fso, drv, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set drv = fso.GetDrive(fso.GetDriveName(drvPath))
s = "Drive " & UCase(drvPath) & " - "
s = s & drv.VolumeName & "<br>"
s = s & "Total Space: " & FormatNumber(drv.TotalSize / 1024, 0)
s = s & " Kb" & "<br>"
s = s & "Free Space: " & FormatNumber(drv.FreeSpace / 1024, 0)
s = s & " Kb" & "<br>"
Response.Write s
End Sub
The following code illustrates the same functionality in JScript:
function ShowDriveInfo1(drvPath)
{
var fso, drv, s ="";
fso = new ActiveXObject("Scripting.FileSystemObject");
drv = fso.GetDrive(fso.GetDriveName(drvPath));
s += "Drive " + drvPath.toUpperCase()+ " - ";
s += drv.VolumeName + "<br>";
s += "Total Space: " + drv.TotalSize / 1024;
s += " Kb" + "<br>";
s += "Free Space: " + drv.FreeSpace / 1024;
s += " Kb" + "<br>";
Response.Write(s);
}
Working with Folders
Common folder tasks and the methods for performing them are described in
the following table.
Task Method
Create a folder. FileSystemObject.CreateFolder
Folder.Delete or
Delete a folder.
FileSystemObject.DeleteFolder
Folder.Move or
Move a folder.
FileSystemObject.MoveFolder
Folder.Copy or
Copy a folder.
FileSystemObject.CopyFolder
Retrieve the name
Folder.Name
of a folder.
Find out if a folder
FileSystemObject.FolderExists
exists on a drive.
Get an instance of
an existing Folder FileSystemObject.GetFolder
object.
Find out the name
of a folder's parent FileSystemObject.GetParentFolderName
folder.
Find out the path of
FileSystemObject.GetSpecialFolder
system folders.
View the sample code to see how many of these methods and properties are used in
FileSystemObject.
The following example demonstrates how to use the Folder and FileSystemObject objects to
manipulate folders and gain information about them in VBScript:
Sub ShowFolderInfo()
Dim fso, fldr, s
' Get instance of FileSystemObject.
Set fso = CreateObject("Scripting.FileSystemObject")
' Get Drive object.
Set fldr = fso.GetFolder("c:")
' Print parent folder name.
Response.Write "Parent folder name is: " & fldr & "<br>"
' Print drive name.
Response.Write "Contained on drive " & fldr.Drive & "<br>"
' Print root file name.
If fldr.IsRootFolder = True Then
Response.Write "This is the root folder." & ""<br>"<br>"
Else
Response.Write "This folder isn't a root folder." & "<br><br>"
End If
' Create a new folder with the FileSystemObject object.
fso.CreateFolder ("C:\Bogus")
Response.Write "Created folder C:\Bogus" & "<br>"
' Print the base name of the folder.
Response.Write "Basename = " & fso.GetBaseName("c:\bogus") & "<br>"
' Delete the newly created folder.
fso.DeleteFolder ("C:\Bogus")
Response.Write "Deleted folder C:\Bogus" & "<br>"
End Sub
This example shows how to use the Folder and FileSystemObject objects
in JScript:
function ShowFolderInfo()
{
var fso, fldr, s = "";
// Get instance of FileSystemObject.
fso = new ActiveXObject("Scripting.FileSystemObject");
// Get Drive object.
fldr = fso.GetFolder("c:");
// Print parent folder name.
Response.Write("Parent folder name is: " + fldr + "<br>");
// Print drive name.
Response.Write("Contained on drive " + fldr.Drive + "<br>");
// Print root file name.
if (fldr.IsRootFolder)
Response.Write("This is the root folder.");
else
Response.Write("This folder isn't a root folder.");
Response.Write("<br><br>");
// Create a new folder with the FileSystemObject object.
fso.CreateFolder ("C:\\Bogus");
Response.Write("Created folder C:\\Bogus" + "<br>");
// Print the base name of the folder.
Response.Write("Basename = " + fso.GetBaseName("c:\\bogus") + "<br>");
// Delete the newly created folder.
fso.DeleteFolder ("C:\\Bogus");
Response.Write("Deleted folder C:\\Bogus" + "<br>");
}
Microsoft® Scripting Library - FileSystemObject
Previous
Working with Files Next
Creating Files
There are three ways to create an empty text file (sometimes referred to as a
"text stream").
The first way is to use the CreateTextFile method. The following example demonstrates how to
create a text file using this method in VBScript:
Dim fso, f1
Set fso = CreateObject("Scripting.FileSystemObject")
Set f1 = fso.CreateTextFile("c:\testfile.txt", True)
To use this method in JScript, use this code:
Dim fso, ts
Const ForWriting = 2
Set fso = CreateObject("Scripting. FileSystemObject")
Set ts = fso.OpenTextFile("c:\test.txt", ForWriting, True)
To create a text file using this method in JScript, use this code:
Once the text file is created, add data to the file using the following three
steps:
Task Method
Write data to an open text file without a
Write
trailing newline character.
Write data to an open text file with a trailing
WriteLine
newline character.
Write one or more blank lines to an open text
WriteBlankLines
file.
View this sample code to see how the Write, WriteLine, and WriteBlankLines methods are used in
FileSystemObject.
To close an open file, use the Close method of the TextStream object.
View this sample code to see how the Close method is used in FileSystemObject.
The following VBScript example demonstrates how to open a file, use all three write methods to add
data to the file, and then close the file:
Sub CreateFile()
Dim fso, tf
Set fso = CreateObject("Scripting.FileSystemObject")
Set tf = fso.CreateTextFile("c:\testfile.txt", True)
' Write a line with a newline character.
tf.WriteLine("Testing 1, 2, 3.")
' Write three newline characters to the file.
tf.WriteBlankLines(3)
' Write a line.
tf.Write ("This is a test.")
tf.Close
End Sub
This example demonstrates how to use the three methods in JScript:
function CreateFile()
{
var fso, tf;
fso = new ActiveXObject("Scripting.FileSystemObject");
tf = fso.CreateTextFile("c:\\testfile.txt", true);
// Write a line with a newline character.
tf.WriteLine("Testing 1, 2, 3.") ;
// Write three newline characters to the file.
tf.WriteBlankLines(3) ;
// Write a line.
tf.Write ("This is a test.");
tf.Close();
}
Reading Files
To read data from a text file, use the Read, ReadLine, or ReadAll method
of the TextStream object. The following table describes which method to
use for various tasks.
Task Method
Read a specified number of characters from a file. Read
Read an entire line (up to, but not including, the
ReadLine
newline character).
Read the entire contents of a text file. ReadAll
View this sample code to see how the ReadAll and ReadLine methods are used in
FileSystemObject.
If you use the Read or ReadLine method and want to skip to a particular portion of data, use the
Skip or SkipLine method. The resulting text of the read methods is stored in a string which can be
displayed in a control, parsed by string functions (such as Left, Right, and Mid), concatenated, and
so forth.
The following VBScript example demonstrates how to open a file, write to it, and then read from it:
Sub ReadFiles
Dim fso, f1, ts, s
Const ForReading = 1
Set fso = CreateObject("Scripting.FileSystemObject")
Set f1 = fso.CreateTextFile("c:\testfile.txt", True)
' Write a line.
Response.Write "Writing file <br>"
f1.WriteLine "Hello World"
f1.WriteBlankLines(1)
f1.Close
' Read the contents of the file.
Response.Write "Reading file <br>"
Set ts = fso.OpenTextFile("c:\testfile.txt", ForReading)
s = ts.ReadLine
Response.Write "File contents = '" & s & "'"
ts.Close
End Sub
This code demonstrates the same thing in JScript:
function ReadFiles()
{
var fso, f1, ts, s;
var ForReading = 1;
fso = new ActiveXObject("Scripting.FileSystemObject");
f1 = fso.CreateTextFile("c:\\testfile.txt", true);
// Write a line.
Response.Write("Writing file <br>");
f1.WriteLine("Hello World");
f1.WriteBlankLines(1);
f1.Close();
// Read the contents of the file.
Response.Write("Reading file <br>");
ts = fso.OpenTextFile("c:\\testfile.txt", ForReading);
s = ts.ReadLine();
Response.Write("File contents = '" + s + "'");
ts.Close();
}
Moving, Copying, and Deleting Files
The FSO object model has two methods each for moving, copying, and
deleting files, as described in the following table.
Task Method
Move a file File.Move or FileSystemObject.MoveFile
Copy a file File.Copy or FileSystemObject.CopyFile
Delete a file File.Delete or FileSystemObject.DeleteFile
View this sample code to see two ways to delete a file in FileSystemObject.
The following VBScript example creates a text file in the root directory of drive C, writes some
information to it, moves it to a directory called \tmp, makes a copy of it in a directory called \temp,
then deletes the copies from both directories.
To run the following example, create directories named \tmp and \temp in the root directory of drive
C:
Sub ManipFiles
Dim fso, f1, f2, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f1 = fso.CreateTextFile("c:\testfile.txt", True)
Response.Write "Writing file <br>"
' Write a line.
f1.Write ("This is a test.")
' Close the file to writing.
f1.Close
Response.Write "Moving file to c:\tmp <br>"
' Get a handle to the file in root of C:\.
Set f2 = fso.GetFile("c:\testfile.txt")
' Move the file to \tmp directory.
f2.Move ("c:\tmp\testfile.txt")
Response.Write "Copying file to c:\temp <br>"
' Copy the file to \temp.
f2.Copy ("c:\temp\testfile.txt")
Response.Write "Deleting files <br>"
' Get handles to files' current location.
Set f2 = fso.GetFile("c:\tmp\testfile.txt")
Set f3 = fso.GetFile("c:\temp\testfile.txt")
' Delete the files.
f2.Delete
f3.Delete
Response.Write "All done!"
End Sub
This code shows the same thing in JScript:
function ManipFiles()
{
var fso, f1, f2, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
f1 = fso.CreateTextFile("c:\\testfile.txt", true);
Response.Write("Writing file <br>");
// Write a line.
f1.Write("This is a test.");
// Close the file to writing.
f1.Close();
Response.Write("Moving file to c:\\tmp <br>");
// Get a handle to the file in root of C:\.
f2 = fso.GetFile("c:\\testfile.txt");
// Move the file to \tmp directory.
f2.Move ("c:\\tmp\\testfile.txt");
Response.Write("Copying file to c:\\temp <br>");
// Copy the file to \temp.
f2.Copy ("c:\\temp\\testfile.txt");
Response.Write("Deleting files <br>");
// Get handles to files' current location.
f2 = fso.GetFile("c:\\tmp\\testfile.txt");
f3 = fso.GetFile("c:\\temp\\testfile.txt");
// Delete the files.
f2.Delete();
f3.Delete();
Response.Write("All done!");
}
Microsoft® Scripting Library - FileSystemObject
FileSystemObject Previous
Sample Code
The sample code described in this section provides a real-world example
that demonstrates many of the features available in the FileSystemObject
object model. This code shows how all the features of the object model
work together, and how to use those features effectively in your own code.
Note that since this code is fairly generic, some additional code and a little tweaking are needed to
make this code actually run on your machine. These changes are necessary because of the different
ways input and output to the user is handled between Active Server Pages and the Windows Scripting
Host.
To run this code on an Active Server Page, use the following steps:
The previous code adds a print procedure that will run on the server side,
but display results on the client side. To run this code on the Windows
Scripting Host, add the following code to the end of the sample code:
Sub Print(x)
WScript.Echo x
End Sub
Main
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
' FileSystemObject Sample Code
'
' Copyright 1998 Microsoft Corporation. All Rights Reserved.
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Option Explicit
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
' Regarding code quality:
'
' 1) The following code does a lot of string manipulation by concatenating short
' strings together with the "&" operator. Since string concatenation
' is expensive, this is a very inefficient way to write code. However, it is a very
' maintainable way to write code, and is used here because this program performs extensive
' disk operations, and because the disk is much slower than the memory operations required to
' concatenate the strings. Keep in mind that this is demonstration code, not production code.
'
' 2) "Option Explicit" is used, because declared variable access is slightly faster than
' undeclared variable access. It also prevents bugs from creeping into your code, such as
' when you misspell DriveTypeCDROM as DriveTypeCDORM.
'
' 3) Error handling is absent from this code, to make the code more readable. Although
' precautions have been taken to ensure that the code will not error in common cases, file
' systems can be unpredictable. In production code, use On Error Resume Next and the
' Err object to trap possible errors.
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
' Some handy global variables
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim TabStop
Dim NewLine
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
' Constants returned by Drive.DriveType
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Const DriveTypeRemovable = 1
Const DriveTypeFixed = 2
Const DriveTypeNetwork = 3
Const DriveTypeCDROM = 4
Const DriveTypeRAMDisk = 5
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
' Constants returned by File.Attributes
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Const FileAttrNormal = 0
Const FileAttrReadOnly = 1
Const FileAttrHidden = 2
Const FileAttrSystem = 4
Const FileAttrVolume = 8
Const FileAttrDirectory = 16
Const FileAttrArchive = 32
Const FileAttrAlias = 64
Const FileAttrCompressed = 128
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
' Constants for opening files
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Const OpenFileForReading = 1
Const OpenFileForWriting = 2
Const OpenFileForAppending = 8
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
' ShowDriveType
'
' Purpose:
'
' Generates a string describing the drive type of a given Drive object.
'
' Demonstrates the following
'
' - Drive.DriveType
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function ShowDriveType(Drive)
Dim S
Select Case Drive.DriveType
Case DriveTypeRemovable
S = "Removable"
Case DriveTypeFixed
S = "Fixed"
Case DriveTypeNetwork
S = "Network"
Case DriveTypeCDROM
S = "CD-ROM"
Case DriveTypeRAMDisk
S = "RAM Disk"
Case Else
S = "Unknown"
End Select
ShowDriveType = S
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
' ShowFileAttr
'
' Purpose:
'
' Generates a string describing the attributes of a file or folder.
'
' Demonstrates the following
'
' - File.Attributes
' - Folder.Attributes
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
If Attr = 0 Then
ShowFileAttr = "Normal"
Exit Function
End If
ShowFileAttr = S
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
' GenerateDriveInformation
'
' Purpose:
'
' Generates a string describing the current state of the available drives.
'
' Demonstrates the following
'
' - FileSystemObject.Drives
' - Iterating the Drives collection
' - Drives.Count
' - Drive.AvailableSpace
' - Drive.DriveLetter
' - Drive.DriveType
' - Drive.FileSystem
' - Drive.FreeSpace
' - Drive.IsReady
' - Drive.Path
' - Drive.SerialNumber
' - Drive.ShareName
' - Drive.TotalSize
' - Drive.VolumeName
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function GenerateDriveInformation(FSO)
Dim Drives
Dim Drive
Dim S
S = "Number of drives:" & TabStop & Drives.Count & NewLine & NewLine
S = S & Drive.DriveLetter
S = S & TabStop & Drive.Path
S = S & TabStop & ShowDriveType(Drive)
S = S & TabStop & Drive.IsReady
If Drive.IsReady Then
If DriveTypeNetwork = Drive.DriveType Then
S = S & TabStop & Drive.ShareName
Else
S = S & TabStop & Drive.VolumeName
End If
End If
S = S & NewLine
Next
GenerateDriveInformation = S
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
' GenerateFileInformation
'
' Purpose:
'
' Generates a string describing the current state of a file.
'
' Demonstrates the following
'
' - File.Path
' - File.Name
' - File.Type
' - File.DateCreated
' - File.DateLastAccessed
' - File.DateLastModified
' - File.Size
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function GenerateFileInformation(File)
Dim S
GenerateFileInformation = S
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
' GenerateFolderInformation
'
' Purpose:
'
' Generates a string describing the current state of a folder.
'
' Demonstrates the following
'
' - Folder.Path
' - Folder.Name
' - Folder.DateCreated
' - Folder.DateLastAccessed
' - Folder.DateLastModified
' - Folder.Size
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function GenerateFolderInformation(Folder)
Dim S
GenerateFolderInformation = S
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
' GenerateAllFolderInformation
'
' Purpose:
'
' Generates a string describing the current state of a
' folder and all files and subfolders.
'
' Demonstrates the following
'
' - Folder.Path
' - Folder.SubFolders
' - Folders.Count
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function GenerateAllFolderInformation(Folder)
Dim S
Dim SubFolders
Dim SubFolder
Dim Files
Dim File
If 1 = Files.Count Then
S = S & "There is 1 file" & NewLine
Else
S = S & "There are " & Files.Count & " files" & NewLine
End If
End If
If 1 = SubFolders.Count Then
S = S & NewLine & "There is 1 sub folder" & NewLine & NewLine
Else
S = S & NewLine & "There are " & SubFolders.Count & " sub folders" & NewLine & NewLine
End If
S = S & NewLine
GenerateAllFolderInformation = S
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
' GenerateTestInformation
'
' Purpose:
'
' Generates a string describing the current state of the C:\Test
' folder and all files and subfolders.
'
' Demonstrates the following
'
' - FileSystemObject.DriveExists
' - FileSystemObject.FolderExists
' - FileSystemObject.GetFolder
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function GenerateTestInformation(FSO)
Dim TestFolder
Dim S
GenerateTestInformation = GenerateAllFolderInformation(TestFolder)
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
' DeleteTestDirectory
'
' Purpose:
'
' Cleans up the test directory.
'
' Demonstrates the following
'
' - FileSystemObject.GetFolder
' - FileSystemObject.DeleteFile
' - FileSystemObject.DeleteFolder
' - Folder.Delete
' - File.Delete
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Sub DeleteTestDirectory(FSO)
Dim TestFolder
Dim SubFolder
Dim File
' Two ways to delete a file:
End Sub
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
' CreateLyrics
'
' Purpose:
'
' Builds a couple of text files in a folder.
'
'
' Demonstrates the following
'
' - FileSystemObject.CreateTextFile
' - TextStream.WriteLine
' - TextStream.Write
' - TextStream.WriteBlankLines
' - TextStream.Close
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Sub CreateLyrics(Folder)
Dim TextStream
Set TextStream = Folder.CreateTextFile("OctopusGarden.txt")
TextStream.Write("Octopus' Garden ") ' Note that this does not add a line feed to the file.
TextStream.WriteLine("(by Ringo Starr)")
TextStream.WriteBlankLines(1)
TextStream.WriteLine("I'd like to be under the sea in an octopus' garden in the shade,")
TextStream.WriteLine("He'd let us in, knows where we've been -- in his octopus' garden in the shade.")
TextStream.WriteBlankLines(2)
TextStream.Close
End Sub
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
' GetLyrics
'
' Purpose:
'
' Displays the contents of the lyrics files.
'
'
' Demonstrates the following
'
' - FileSystemObject.OpenTextFile
' - FileSystemObject.GetFile
' - TextStream.ReadAll
' - TextStream.Close
' - File.OpenAsTextStream
' - TextStream.AtEndOfStream
' - TextStream.ReadLine
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function GetLyrics(FSO)
Dim TextStream
Dim S
Dim File
' There are several ways to open a text file, and several ways to read the
' data out of a file. Here's two ways to do each:
GetLyrics = S
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
' BuildTestDirectory
'
' Purpose:
'
' Builds a directory hierarchy to demonstrate the FileSystemObject.
'
' We'll build a hierarchy in this order:
'
' C:\Test
' C:\Test\ReadMe.txt
' C:\Test\Beatles
' C:\Test\Beatles\OctopusGarden.txt
' C:\Test\Beatles\BathroomWindow.txt
'
'
' Demonstrates the following
'
' - FileSystemObject.DriveExists
' - FileSystemObject.FolderExists
' - FileSystemObject.CreateFolder
' - FileSystemObject.CreateTextFile
' - Folders.Add
' - Folder.CreateTextFile
' - TextStream.WriteLine
' - TextStream.Close
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function BuildTestDirectory(FSO)
Dim TestFolder
Dim SubFolders
Dim SubFolder
Dim TextStream
' Bail out if (a) the drive does not exist, or if (b) the directory being built
' already exists.
If FSO.FolderExists(TestFilePath) Then
BuildTestDirectory = False
Exit Function
End If
CreateLyrics SubFolder
BuildTestDirectory = True
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
' The main routine
'
' First, it creates a test directory, along with some subfolders and files.
' Then, it dumps some information about the available disk drives and
' about the test directory, and then cleans everything up again.
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Sub Main
Dim FSO
DeleteTestDirectory(FSO)
End Sub
Microsoft® Visual Basic® Scripting Edition
Language Reference
VBScript Features
Category Keywords
Array
Dim, Private, Public, ReDim
Array handling IsArray
Erase
LBound, UBound
Assignments Set
Comments Comments using ' or Rem
Empty
Nothing
Constants/Literals
Null
True, False
Do...Loop
For...Next
For Each...Next
Control flow If...Then...Else
Select Case
While...Wend
With
Abs
Asc, AscB, AscW
Chr, ChrB, ChrW
CBool, CByte
CCur, CDate
CDbl, CInt
Conversions
CLng, CSng, CStr
DateSerial, DateValue
Hex, Oct
Fix, Int
Sgn
TimeSerial, TimeValue
Date, Time
DateAdd, DateDiff, DatePart
DateSerial, DateValue
Day, Month, MonthName
Dates/Times
Weekday, WeekdayName, Year
Hour, Minute, Second
Now
TimeSerial, TimeValue
Class
Const
Declarations Dim, Private, Public, ReDim
Function, Sub
Property Get, Property Let, Property Set
On Error
Error Handling
Err
Eval
Execute
Expressions RegExp
Replace
Test
FormatCurrency
FormatDateTime
Formatting Strings
FormatNumber
FormatPercent
InputBox
Input/Output LoadPicture
MsgBox
Empty
False
Literals Nothing
Null
True
Atn, Cos, Sin, Tan
Math Exp, Log, Sqr
Randomize, Rnd
Eval Function
Miscellaneous Execute Statement
RGB Function
CreateObject
Err Object
Objects
GetObject
RegExp
Addition (+), Subtraction (-)
Exponentiation (^)
Modulus arithmetic (Mod)
Multiplication (*), Division (/)
Integer Division (\)
Negation (-)
String concatenation (&)
Operators
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
Call
Function, Sub
Procedures Property Get, Property Let, Property Set
Abs
Rounding Int, Fix, Round
Sgn
ScriptEngine
ScriptEngineBuildVersion
Script Engine ID
ScriptEngineMajorVersion
ScriptEngineMinorVersion
Asc, AscB, AscW
Chr, ChrB, ChrW
Filter, InStr, InStrB
InStrRev
Join
Len, LenB
LCase, UCase
Left, LeftB
Strings Mid, MidB
Right, RightB
Replace
Space
Split
StrComp
String
StrReverse
LTrim, RTrim, Trim
IsArray
IsDate
IsEmpty
IsNull
Variants
IsNumeric
IsObject
TypeName
VarType
Microsoft® Visual Basic® Scripting Edition Visual
Basic for
Language Reference
Applications
Features not in
VBScript
VBScript Features
Language Reference
not in Visual Basic
for Applications
Category Feature/Keyword
Declarations Class
Eval
Miscellaneous
Execute
Objects RegExp
ScriptEngine
Script Engine ScriptEngineBuildVersion
Identification ScriptEngineMajorVersion
ScriptEngineMinorVersion
Microsoft® Visual Basic® Scripting Edition
Microsoft
Scripting
Language Reference
Run-Time Library
Reference
Features
Category Feature/Keyword
Drives
Collections Files
Folders
Data Storage Dictionary
Add
Exists
Items, Keys
Dictionary
Remove, RemoveAll
Count
Item, Key
Drive
File
File System FileSystemObject
Folder
TextStream
BuildPath
CopyFile, CopyFolder
CreateFolder,CreateTextFile
DeleteFile,DeleteFolder
DriveExists, FileExists, FolderExists
GetAbsolutePathName, GetBaseName
FileSystemObject GetDrive, GetDriveName
GetFile, GetExtensionName GetFileName
GetFolder, GetParentFolderName
GetSpecialFolder
GetTempName
MoveFile, MoveFolder
OpenTextFile
Drives
AvailableSpace
Count
DriveLetter
DriveType
FileSystem
FreeSpace
Drive, Drives IsReady
Item
RootFolder
SerialNumber
ShareName
TotalSize
VolumeName
Add
Attributes
Copy, Delete, Move
Count
OpenAsTextStream
DateCreated, DateLastAccessed,
File, Files
DateLastModified
Folder, Folders
Drive
Item
ParentFolder
Name, Path
ShortName, ShortPath
Size
Close
Read, ReadAll, ReadLine
TextStream Skip, SkipLine
Write, WriteBlankLines, WriteLine
AtEndOfLine, AtEndOfStream
Column, Line
Microsoft® Visual Basic® Scripting Edition Abs Language Reference
Version 1
Function
See Also
Description
Syntax
Abs(number)
Remarks
The following example uses the Abs function to compute the absolute value
of a number:
Dim MyNumber
MyNumber = Abs(50.3) ' Returns 50.3.
MyNumber = Abs(-50.3) ' Returns 50.3.
Microsoft® Visual Basic® Scripting Edition + Scripting Run-Time Reference
Version 1
Operator
See Also
Description
Syntax
Part Description
result Any numeric variable.
expression1 Any expression.
expression2 Any expression.
Remarks
Although you can also use the + operator to concatenate two character
strings, you should use the & operator for concatenation to eliminate
ambiguity and provide self-documenting code.
When you use the + operator, you may not be able to determine whether addition or string
concatenation will occur.
The underlying subtype of the expressions determines the behavior of the + operator in the following
way:
If Then
Both expressions are numeric Add.
Both expressions are strings Concatenate.
Add.
One expression is numeric and the other is a string
If one or both expressions are Null expressions, result is Null. If both expressions are Empty, result
is an Integer subtype. However, if only one expression is Empty, the other expression is returned
unchanged as result.
Microsoft® Visual Basic® Scripting Edition And Language Reference
Version 1
Operator
See Also
Description
Syntax
Part Description
result Any numeric variable.
expression1 Any expression.
expression2 Any expression.
Remarks
If, and only if, both expressions evaluate to True, result is True. If either
expression evaluates to False, result is False. The following table illustrates
how result is determined:
Description
Syntax
Array(arglist)
Remarks
Dim A
A = Array(10,20,30)
B = A(2) ' B is now 30.
NoteVersion Version A variable that is not declared as an array
can still contain an array. Although a Variant variable
containing an array is conceptually different from an array
variable containing Variant elements, the array elements are
accessed in the same way.
Microsoft® Visual Basic® Scripting Edition Asc Language Reference
Version 1
Function
See Also
Description
Returns the ANSI character code corresponding to the first letter in a string.
Syntax
Asc(string)
The string argument is any valid string expression. If the string contains no
characters, a run-time error occurs.
Remarks
In the following example, Asc returns the ANSI character code of the first
letter of each string:
Dim MyNumber
MyNumber = Asc("A") ' Returns 65.
MyNumber = Asc("a") ' Returns 97.
MyNumber = Asc("Apple") ' Returns 65.
Description
Syntax
variable = value
The = operator syntax has these parts:
Part Description
variable Any variable or any writable property.
value Any numeric or string literal, constant, or expression.
Remarks
The name on the left side of the equal sign can be a simple scalar variable
or an element of an array. Properties on the left side of the equal sign can
only be those properties that are writable at run time.
Microsoft® Visual Basic® Scripting Edition Atn Language Reference
Version 1
Function
See Also
Description
Syntax
Atn(number)
Remarks
The Atn function takes the ratio of two sides of a right triangle (number)
and returns the corresponding angle in radians. The ratio is the length of the
side opposite the angle divided by the length of the side adjacent to the
angle. The range of the result is -pi/2 to pi/2 radians.
Dim pi
pi = 4 * Atn(1) ' Calculate the value of pi.
Syntax
Part Description
Optional keyword. If specified, you must enclose
argumentlist in parentheses. For example:
Call
Call MyProc(0)
Remarks
You are not required to use the Call keyword when calling a procedure.
However, if you use the Call keyword to call a procedure that requires
arguments, argumentlist must be enclosed in parentheses. If you omit the
Call keyword, you also must omit the parentheses around argumentlist. If
you use either Call syntax to call any intrinsic or user-defined function, the
function's return value is discarded.
Call MyFunction("Hello World")
Function MyFunction(text)
MsgBox text
End Function
Microsoft® Visual Basic® Scripting Edition CBool Language Reference
Version 1
Function
See Also
Description
Syntax
CBool(expression)
The expression argument is any valid expression.
Remarks
Dim A, B, Check
A = 5: B = 5 ' Initialize variables.
Check = CBool(A = B) ' Check contains True.
A = 0 ' Define variable.
Check = CBool(A) ' Check contains False.
Microsoft® Visual Basic® Scripting Edition CByte Language Reference
Version 1
Function
See Also
Description
Syntax
CByte(expression)
The expression argument is any valid expression.
Remarks
In general, you can document your code using the subtype conversion
functions to show that the result of some operation should be expressed as a
particular data type rather than the default data type. For example, use
CByte to force byte arithmetic in cases where currency, single-precision,
double-precision, or integer arithmetic normally would occur.
Use the CByte function to provide internationally aware conversions from any other data type to a
Byte subtype. For example, different decimal separators are properly recognized depending on the
locale setting of your system, as are different thousand separators.
If expression lies outside the acceptable range for the Byte subtype, an error occurs. The following
example uses the CByte function to convert an expression to a byte:
Description
Syntax
CCur(expression)
The expression argument is any valid expression.
Remarks
In general, you can document your code using the subtype conversion
functions to show that the result of some operation should be expressed as a
particular data type rather than the default data type. For example, use
CCur to force currency arithmetic in cases where integer arithmetic
normally would occur.
You should use the CCur function to provide internationally aware conversions from any other data
type to a Currency subtype. For example, different decimal separators and thousands separators are
properly recognized depending on the locale setting of your system.
The following example uses the CCur function to convert an expression to a Currency:
Description
Syntax
CDate(date)
Remarks
Description
Syntax
CDbl(expression)
Remarks
In general, you can document your code using the subtype conversion
functions to show that the result of some operation should be expressed as a
particular data type rather than the default data type. For example, use
CDbl or CSng to force double-precision or single-precision arithmetic in
cases where currency or integer arithmetic normally would occur.
Description
Returns the character associated with the specified ANSI character code.
Syntax
Chr(charcode)
Remarks
The following example uses the Chr function to return the character
associated with the specified character code:
Dim MyChar
MyChar = Chr(65) ' Returns A.
MyChar = Chr(97) ' Returns a.
MyChar = Chr(62) ' Returns >.
MyChar = Chr(37) ' Returns %.
Note The ChrB function is used with byte data contained in a
string. Instead of returning a character, which may be one or two
bytes, ChrB always returns a single byte. ChrW is provided for
32-bit platforms that use Unicode characters. Its argument is a
Unicode (wide) character code, thereby avoiding the conversion
from ANSI to Unicode.
Microsoft® Visual Basic® Scripting Edition CInt Language Reference
Version 1
Function
See Also
Description
Syntax
CInt(expression)
Remarks
In general, you can document your code using the subtype conversion
functions to show that the result of some operation should be expressed as a
particular data type rather than the default data type. For example, use CInt
or CLng to force integer arithmetic in cases where currency, single-
precision, or double-precision arithmetic normally would occur.
If expression lies outside the acceptable range for the Integer subtype, an
error occurs.
Note CInt differs from the Fix and Int functions, which
truncate, rather than round, the fractional part of a number.
When the fractional part is exactly 0.5, the CInt function always
rounds it to the nearest even number. For example, 0.5 rounds to
0, and 1.5 rounds to 2.
Microsoft® Visual Basic® Scripting Edition Class Language Reference
Version 5
Object
See Also Events
Description
Remarks
Dim X
Set X = New classname
or
Dim X
X = New classname
or
Description
Syntax
Class name
statements
End Class
Part Description
name Required. Name of the Class; follows standard variable naming conventions.
Required. One or more statements that define the variables, properties, and methods of
statements
the Class.
Remarks
Description
Syntax
object.Clear
The object is always the Err object.
Remarks
Use Clear to explicitly clear the Err object after an error has been handled.
This is necessary, for example, when you use deferred error handling with
On Error Resume Next. VBScript calls the Clear method automatically
whenever any of the following statements is executed:
Description
Syntax
CLng(expression)
Remarks
In general, you can document your code using the subtype conversion
functions to show that the result of some operation should be expressed as a
particular data type rather than the default data type. For example, use CInt
or CLng to force integer arithmetic in cases where currency, single-
precision, or double-precision arithmetic normally would occur.
If expression lies outside the acceptable range for the Long subtype, an
error occurs.
Note CLng differs from the Fix and Int functions, which
truncate, rather than round, the fractional part of a number.
When the fractional part is exactly 0.5, the CLng function
always rounds it to the nearest even number. For example, 0.5
rounds to 0, and 1.5 rounds to 2.
Microsoft® Visual Basic® Scripting Edition
Since these constants are built into VBScript, you don't have to define them
before using them. Use them anywhere in your code to represent the values
shown for each.
Description
Syntax
Part Description
result Any variable.
expression1 Any expression.
expression2 Any expression.
Remarks
Description
Syntax
Part Description
Optional. Keyword used at script level to declare
Public constants that are available to all procedures in all
scripts. Not allowed in procedures.
Optional. Keyword used at script level to declare
constants that are available only within the script
Private
where the declaration is made. Not allowed in
procedures.
Required. Name of the constant; follows standard
constname
variable naming conventions.
Required. Literal or other constant, or any
expression combination that includes all arithmetic or logical
operators except Is.
Remarks
You can't use variables, user-defined functions, or intrinsic VBScript functions (such as Chr) in
constant declarations. By definition, they can't be constants. You also can't create a constant from any
expression that involves an operator, that is, only simple constants are allowed. Constants declared in
a Sub or Function procedure are local to that procedure. A constant declared outside a procedure is
defined throughout the script in which it is declared. You can use constants anywhere you can use an
expression. The following code illustrates the use of the Const statement:
Description
Syntax
Cos(number)
The number argument can be any valid numeric expression that expresses an angle in radians.
Remarks
The Cos function takes an angle and returns the ratio of two sides of a right
triangle. The ratio is the length of the side adjacent to the angle divided by
the length of the hypotenuse. The result lies in the range -1 to 1.
To convert degrees to radians, multiply degrees by pi/180. To convert radians to degrees, multiply
radians by 180/pi.
The following example uses the Cos function to return the cosine of an angle:
Description
Syntax
CreateObject(servername.typename [, location])
The CreateObject function syntax has these parts:
Part Description
Required. The name of the application providing the
servername
object.
typename Required.The type or class of the object to create.
Optional. The name of the network server where the
location object is to be created. This feature is available in
version 5.1 or later.
Remarks
Dim ExcelSheet
Set ExcelSheet = CreateObject("Excel.Sheet")
This code starts the application that creates the object (in this case, a
Microsoft Excel spreadsheet). Once an object is created, refer to it in code
using the object variable you defined. As shown in the following example,
you can access properties and methods of the new object using the object
variable, ExcelSheet, and other Excel objects, including the Application
object and the ActiveSheet.Cells collection:
Function GetVersion
Dim XLApp
Set XLApp = CreateObject("Excel.Application", "MyServ
GetVersion = XLApp.Version
End Function
An error occurs if the specified remote server does not exist or cannot be
found.
Microsoft® Visual Basic® Scripting Edition CSng Language Reference
Version 1
Function
See Also
Description
Syntax
CSng(expression)
Remarks
In general, you can document your code using the data type conversion
functions to show that the result of some operation should be expressed as a
particular data type rather than the default data type. For example, use
CDbl or CSng to force double-precision or single-precision arithmetic in
cases where currency or integer arithmetic normally would occur.
If expression lies outside the acceptable range for the Single subtype, an
error occurs.
Description
Syntax
CStr(expression)
Remarks
In general, you can document your code using the data type conversion
functions to show that the result of some operation should be expressed as a
particular data type rather than the default data type. For example, use CStr
to force the result to be expressed as a String.
You should use the CStr function instead of Str to provide internationally
aware conversions from any other data type to a String subtype. For
example, different decimal separators are properly recognized depending on
the locale setting of your system.
If
expression CStr returns
is
Boolean A String containing True or False.
A String containing a date in the short-date format
Date
of your system.
Null A run-time error.
Empty A zero-length String ("").
A String containing the word Error followed by the
Error
error number.
Other
A String containing the number.
numeric
The following example uses the CStr function to convert a numeric value
to a String:
Constants
See Also
Since these constants are built into VBScript, you don't have to define them
before using them. Use them anywhere in your code to represent the values
shown for each.
Since these constants are built into VBScript, you don't have to define them
before using them. Use them anywhere in your code to represent the values
shown for each.
Description
Syntax
Date
Remarks
The following example uses the Date function to return the current system
date:
Dim MyDate
MyDate = Date ' MyDate contains the current system date.
Microsoft® Visual Basic® Scripting Edition
Language Reference
DateAdd Function Version 2
See Also
Description
Syntax
Part Description
Required. String expression that is the interval you want
interval
to add. See Settings section for values.
Required. Numeric expression that is the number of
interval you want to add. The numeric expression can
number
either be positive, for dates in the future, or negative,
for dates in the past.
Required. Variant or literal representing the date to
date
which interval is added.
Settings
Setting Description
yyyy Year
q Quarter
m Month
y Day of year
d Day
w Weekday
ww Week of year
h Hour
n Minute
s Second
Remarks
You can use the DateAdd function to add or subtract a specified time
interval from a date. For example, you can use DateAdd to calculate a date
30 days from today or a time 45 minutes from now. To add days to date,
you can use Day of Year ("y"), Day ("d"), or Weekday ("w").
The DateAdd function won't return an invalid date. The following example adds one month to
January 31:
If number isn't a Long value, it is rounded to the nearest whole number before being evaluated.
Microsoft® Visual Basic® Scripting Edition
Language Reference
DateDiff Function Version 2
See Also
Description
Syntax
Part Description
Required. String expression that is the interval
you want to use to calculate the differences
interval
between date1 and date2. See Settings section
for values.
Required. Date expressions. Two dates you want
date1, date2
to use in the calculation.
Optional. Constant that specifies the day of the
firstdayofweek week. If not specified, Sunday is assumed. See
Settings section for values.
Optional. Constant that specifies the first week
of the year. If not specified, the first week is
firstweekofyear
assumed to be the week in which January 1
occurs. See Settings section for values.
Settings
Setting Description
yyyy Year
q Quarter
m Month
y Day of year
d Day
w Weekday
ww Week of year
h Hour
n Minute
s Second
The firstdayofweek argument can have the following values:
Remarks
You can use the DateDiff function to determine how many specified time
intervals exist between two dates. For example, you might use DateDiff to
calculate the number of days between two dates, or the number of weeks
between today and the end of the year.
To calculate the number of days between date1 and date2, you can use either 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 in 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.
When comparing December 31 to January 1 of the immediately succeeding year, DateDiff for Year
("yyyy") returns 1 even though only a day has elapsed.
The following example uses the DateDiff function to display the number of days between a given
date and today:
Function DiffADate(theDate)
DiffADate = "Days from today: " & DateDiff("d", Now, theDate)
End Function
Microsoft® Visual Basic® Scripting Edition
Language Reference
DatePart Function Version 2
See Also
Description
Syntax
Part Description
Required. String expression that is the interval
interval of time you want to return. See Settings section
for values.
date Required. Date expression you want to evaluate.
Optional. Constant that specifies the day of the
firstdayof week week. If not specified, Sunday is assumed. See
Settings section for values.
Optional. Constant that specifies the first week
of the year. If not specified, the first week is
firstweekofyear
assumed to be the week in which January 1
occurs. See Settings section for values.
Settings
Setting Description
yyyy Year
q Quarter
m Month
y Day of year
d Day
w Weekday
ww Week of year
h Hour
n Minute
s Second
The firstdayofweek argument can have the following values:
You can use the DatePart function to evaluate a date and return a specific
interval of time. For example, you might use DatePart to calculate the day
of the week or the current hour.
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 in your code each time the date
expression is evaluated. This makes it possible to write code that can be
used in different years.
This example takes a date and, using the DatePart function, displays the
quarter of the year in which it occurs.
Function GetQuarter(TheDate)
GetQuarter = DatePart("q", TheDate)
End Function
Microsoft® Visual Basic® Scripting Edition
Description
Returns a Variant of subtype Date for a specified year, month, and day.
Syntax
Part Description
Number between 100 and 9999, inclusive, or a numeric
year
expression.
month Any numeric expression.
day Any numeric expression.
Remarks
To specify a date, such as December 31, 1991, the range of numbers for
each DateSerial argument should be in the accepted range for the unit; that
is, 1–31 for days and 1–12 for months. However, you can also specify
relative dates for each argument using any numeric expression that
represents some number of days, months, or years before or after a certain
date.
When any argument exceeds the accepted range for that argument, it
increments to the next larger unit as appropriate. For example, if you
specify 35 days, it is evaluated as one month and some number of days,
depending on where in the year it is applied. However, if any single
argument is outside the range -32,768 to 32,767, or if the date specified by
the three arguments, either directly or by expression, falls outside the
acceptable range of dates, an error occurs.
Microsoft® Visual Basic® Scripting Edition
Description
Syntax
DateValue(date)
The date argument is normally a string expression representing a date from January 1, 100 through
December 31, 9999. However, date can also be any expression that can represent a date, a time, or
both a date and time, in that range.
Remarks
If the date argument includes time information, DateValue doesn't return it.
However, if date includes invalid time information (such as "89:98"), an
error occurs.
If date is a string that includes only numbers separated by valid date separators, DateValue
recognizes the order for month, day, and year according to the short date format you specified for
your system. DateValue also recognizes unambiguous dates that contain month names, either in long
or abbreviated form. For example, in addition to recognizing 12/30/1991 and 12/30/91, DateValue
also recognizes December 30, 1991 and Dec 30, 1991.
If the year part of date is omitted, DateValue uses the current year from your computer's system date.
The following example uses the DateValue function to convert a string to a date. You can also use
date literals to directly assign a date to a Variant variable, for example, MyDate = #9/11/63#.
Dim MyDate
MyDate = DateValue("September 11, 1963") ' Return a da
Microsoft® Visual Basic® Scripting Edition Day Language Reference
Version 1
Function
See Also
Description
Returns a whole number between 1 and 31, inclusive, representing the day
of the month.
Syntax
Day(date)
The date argument is any expression that can represent a date. If date contains Null, Null is returned.
The following example uses the Day function to obtain the day of the month from a specified date:
Dim MyDay
MyDay = Day("October 19, 1962") ' MyDay contains 19.
Microsoft® Visual Basic® Scripting Edition
Description
Syntax
object.Description [= stringexpression]
The Description property syntax has these parts:
Part Description
object Always the Err object.
A string expression containing a description of
stringexpression
the error.
Remarks
Description
Syntax
Part Description
varname Name of the variable; follows standard variable naming conventions.
Dimensions of an array variable; up to 60 multiple dimensions may be declared. The
subscripts argument uses the following syntax:
Remarks
Variables declared with Dim at the script level are available to all
procedures within the script. At the procedure level, variables are
available only within the procedure.
You can also use the Dim statement with empty parentheses to
declare a dynamic array. After declaring a dynamic array, use the
ReDim statement within a procedure to define the number of
dimensions and elements in the array. If you try to redeclare a
dimension for an array variable whose size was explicitly
specified in a Dim statement, an error occurs.
Tip When you use the Dim statement in a procedure, you generally put the Dim statement at the
beginning of the procedure.
Description
Syntax
result = number1/number2
The / operator syntax has these parts:
Part Description
result Any numeric variable.
number1 Any numeric expression.
number2 Any numeric expression.
Remarks
Description
Syntax
Do
[statements]
[Exit Do]
[statements]
Loop [{While | Until} condition]
Part Description
Numeric or string expression that is True or False. If
condition
condition is Null, condition is treated as False.
One or more statements that are repeated while or
statements
until condition is True.
Remarks
See Also
Description
Description
Syntax
Part Description
result Any numeric variable.
expression1 Any expression.
expression2 Any expression.
Remarks
Description
Syntax
Erase array
The array argument is the name of the array variable to be erased.
Remarks
Dim NumArray(9)
Dim DynamicArray()
ReDim DynamicArray(9) ' Allocate storage space.
Erase NumArray ' Each element is reinitialized.
Erase DynamicArray ' Free memory used by array.
Microsoft® Visual Basic® Scripting Edition Err Language Reference
Version 1
Object
See Also Properties Methods
Description
Contains information about run-time errors. Accepts the Raise and Clear
methods for generating and clearing run-time errors.
Remarks
The Err object is an intrinsic object with global scope — there is no need to
create an instance of it in your code. The properties of the Err object are set
by the generator of an error — Visual Basic, an Automation object, or the
VBScript programmer.
The default property of the Err object is Number. Err.Number contains an integer and can be used
by an Automation object to return an SCODE.
When a run-time error occurs, the properties of the Err object are filled with information that
uniquely identifies the error and information that can be used to handle it. To generate a run-time
error in your code, use the Raise method.
The Err object's properties are reset to zero or zero-length strings ("") after an On Error Resume
Next statement. The Clear method can be used to explicitly reset Err.
Description
Syntax
[result = ]Eval(expression)
The Eval function syntax has these parts:
Part Description
Optional. Variable to which return value assignment
result is made. If result is not specified, consider using the
Execute statement instead.
Required. String containing any legal VBScript
expression
expression.
Remarks
Description
Syntax
object.Execute(string)
Part Description
object Required. Always the name of a RegExp object.
string Required. The text string upon which the regular expression is executed.
Remarks
The actual pattern for the regular expression search is set using
the Pattern property of the RegExp object.
Description
Syntax
Execute statement
The required statement argument is a string expression containing one or more statements for
execution. Include multiple statements in the statement argument, using colons or embedded line
breaks to separate them.
Remarks
The context in which the Execute statement is invoked determines what objects and variables are
available to the code being run. In-scope objects and variables are available to code running in an
Execute statement. However, it is important to understand that if you execute code that creates a
procedure, that procedure does not inherit the scope of the procedure in which it occurred.
Like any procedure, the new procedure's scope is global, and it inherits everything in the global
scope. Unlike any other procedure, its context is not global scope, so it can only be executed in the
context of the procedure where the Execute statement occurred. However, if the same Execute
statement is invoked outside of a procedure (i.e., in global scope), not only does it inherit everything
in global scope, but it can also be called from anywhere, since its context is global. The following
example illustrates this behavior:
Dim X ' Declare X in global scope.
X = "Global" ' Assign global X a value.
Sub Proc1 ' Declare procedure.
Dim X ' Declare X in local scope.
X = "Local" ' Assign local X a value.
' The Execute statement here creates a
' procedure that, when invoked, prints X.
' It print the global X because Proc2
' inherits everything in global scope.
Execute "Sub Proc2: Print X: End Sub"
Print Eval("X") ' Print local X.
Proc2 ' Invoke Proc2 in Proc1's scope.
End Sub
Proc2 ' This line causes an error since
' Proc2 is unavailable outside Proc1.
Proc1 ' Invoke Proc1.
Execute "Sub Proc2: Print X: End Sub"
Proc2 ' This invocation succeeds because Proc2
' is now available globally.
The following example shows how the Execute statement can be rewritten
so you don't have to enclose the entire procedure in the quotation marks:
Description
Syntax
Exit Do
Exit For
Exit Function
Exit Property
Exit Sub
Statement Description
Provides a way to exit a Do...Loop statement. It can
be used only inside a Do...Loop statement. Exit Do
transfers control to the statement following the Loop
Exit Do
statement. When used within nested Do...Loop
statements, Exit Do transfers control to the loop that
is one nested level above the loop where it occurs.
Provides a way to exit a For loop. It can be used
only in a For...Next or For Each...Next loop. Exit
For transfers control to the statement following the
Exit For
Next statement. When used within nested For loops,
Exit For transfers control to the loop that is one
nested level above the loop where it occurs.
Immediately exits the Function procedure in which
Exit it appears. Execution continues with the statement
Function following the statement that called the Function.
Sub RandomLoop
Dim I, MyNum
Do ' Set up infinite loop.
For I = 1 To 1000 ' Loop 1000 times.
MyNum = Int(Rnd * 100) ' Generate random numbers.
Select Case MyNum ' Evaluate random number.
Case 17: MsgBox "Case 17"
Exit For ' If 17, exit For...Next.
Case 29: MsgBox "Case 29"
Exit Do ' If 29, exit Do...Loop.
Case 54: MsgBox "Case 54"
Exit Sub ' If 54, exit Sub procedure.
End Select
Next
Loop
End Sub
Microsoft® Visual Basic® Scripting Edition Exp Language Reference
Version 1
Function
See Also
Description
Syntax
Exp(number)
The number argument can be any valid numeric expression.
Remarks
Note The Exp function complements the action of the Log function and is sometimes
referred to as the antilogarithm.
The following example uses the Exp function to return e raised to a power:
Description
Syntax
result = number^exponent
The ^ operator syntax has these parts:
Part Description
result Any numeric variable.
number Any numeric expression.
exponent Any numeric expression.
Remarks
See Also
Description
Description
Syntax
Part Description
Required. One-dimensional array of strings to be
InputStrings
searched.
Value Required. String to search for.
Optional. Boolean value indicating whether to
return substrings that include or exclude Value. If
Include is True, Filter returns the subset of the
Include
array that contains Value as a substring. If Include
is False, Filter returns the subset of the array that
does not contain Value as a substring.
Optional. Numeric value indicating the kind of
Compare string comparison to use. See Settings section for
values.
Settings
Remarks
The array returned by the Filter function contains only enough elements to
contain the number of matched items.
The following example uses the Filter function to return the array
containing the search criteria "Mon":
Dim MyIndex
Dim MyArray (3)
MyArray(0) = "Sunday"
MyArray(1) = "Monday"
MyArray(2) = "Tuesday"
MyIndex = Filter(MyArray, "Mon") ' MyIndex(0) contains
Microsoft® Visual Basic® Scripting Edition
Property
See Also Applies To
Description
Syntax
object.FirstIndex
The object argument is always a Match object.
Remarks
The FirstIndex property uses a zero-based offset from the beginning of the
search string. In other words, the first character in the string is identified as
character zero (0). The following code illustrates the use of the FirstIndex
property:
Description
Syntax
Int(number)
Fix(number)
The number argument can be any valid numeric expression. If number contains Null, Null is
returned.
Remarks
Both Int and Fix remove the fractional part of number and return the
resulting integer value.
The difference between Int and Fix is that if number is negative, Int returns the first negative integer
less than or equal to number, whereas Fix returns the first negative integer greater than or equal to
number. For example, Int converts -8.4 to -9, and Fix converts -8.4 to -8.
Sgn(number) * Int(Abs(number))
The following examples illustrate how the Int and Fix functions return
integer portions of numbers:
Description
Syntax
Part Description
Numeric variable used as a loop counter. The
counter variable can't be an array element or an element of a
user-defined type.
start Initial value of counter.
end Final value of counter.
Amount counter is changed each time through the
step
loop. If not specified, step defaults to one.
One or more statements between For and Next that
statements
are executed the specified number of times.
Remarks
The step argument can be either positive or negative. The value of the step
argument determines loop processing as follows:
Value Loop executes if
Positive or 0 counter <= end
Negative counter >= end
Once the loop starts and all statements in the loop have executed, step is added to counter. At this
point, either the statements in the loop execute again (based on the same test that caused the loop to
execute initially), or the loop is exited and execution continues with the statement following the Next
statement.
Tip Changing the value of counter while inside a loop can make
it more difficult to read and debug your code.
Exit For can only be used within a For Each...Next or For...Next control structure to provide an
alternate way to exit. Any number of Exit For statements may be placed anywhere in the loop. Exit
For is often used with the evaluation of some condition (for example, If...Then), and transfers
control to the statement immediately following Next.
You can nest For...Next loops by placing one For...Next loop within another. Give each loop a
unique variable name as its counter. The following construction is correct:
For I = 1 To 10
For J = 1 To 10
For K = 1 To 10
. . .
Next
Next
Next
For
Microsoft® Visual Basic® Scripting Edition
Language Reference
Each...Next Version 2
Statement
See Also
Description
Syntax
Part Description
Variable used to iterate through the elements of the
collection or array. For collections, element can only
element be a Variant variable, a generic Object variable, or
any specific Automation object variable. For arrays,
element can only be a Variant variable.
group Name of an object collection or array.
One or more statements that are executed on each
statements
item in group.
Remarks
The For Each block is entered if there is at least one element in group.
Once the loop has been entered, all the statements in the loop are executed
for the first element in group. As long as there are more elements in group,
the statements in the loop continue to execute for each element. When there
are no more elements in group, the loop is exited and execution continues
with the statement following the Next statement.
The Exit For can only be used within a For Each...Next or For...Next control structure to provide an
alternate way to exit. Any number of Exit For statements may be placed anywhere in the loop. The
Exit For is often used with the evaluation of some condition (for example, If...Then), and transfers
control to the statement immediately following Next.
You can nest For Each...Next loops by placing one For Each...Next loop within another. However,
each loop element must be unique.
Function ShowFolderList(folderspec)
Dim fso, f, f1, fc, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(folderspec)
Set fc = f.Files
For Each f1 in fc
s = s & f1.name
s = s & "<BR>"
Next
ShowFolderList = s
End Function
Microsoft® Visual Basic® Scripting Edition
Description
Syntax
FormatCurrency(Expression[,NumDigitsAfterDecimal
[,IncludeLeadingDigit [,UseParensForNegativeNumbers [,GroupDigits]]]])
The FormatCurrency function syntax has these parts:
Part Description
Required. Expression to be
Expression
formatted.
Optional. Numeric value
indicating how many places to
the right of the decimal are
NumDigitsAfterDecimal displayed. Default value is -1,
which indicates that the
computer's regional settings are
used.
Optional. Tristate constant that
indicates whether or not a
IncludeLeadingDigit leading zero is displayed for
fractional values. See Settings
section for values.
Optional. Tristate constant that
indicates whether or not to
UseParensForNegativeNumbers place negative values within
parentheses. See Settings
section for values.
Optional. Tristate constant that
indicates whether or not
numbers are grouped using the
GroupDigits
group delimiter specified in the
computer's regional settings.
See Settings section for values.
Settings
Remarks
When one or more optional arguments are omitted, values for omitted
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.
Dim MyCurrency
MyCurrency = FormatCurrency(1000) ' MyCurrency conta
Microsoft® Visual Basic® Scripting Edition
Description
Syntax
FormatDateTime(Date[, NamedFormat])
The FormatDateTime function syntax has these parts:
Part Description
Date Required. Date expression to be formatted.
Optional. Numeric value that indicates the
NamedFormat date/time format used. If omitted,
vbGeneralDate is used.
Settings
Remarks
Function GetCurrentDate
' FormatDateTime formats Date in long date.
GetCurrentDate = FormatDateTime(Date, 1)
End Function
Microsoft® Visual Basic® Scripting Edition
Description
Syntax
FormatNumber(Expression [,NumDigitsAfterDecimal
[,IncludeLeadingDigit [,UseParensForNegativeNumbers [,GroupDigits]]]])
The FormatNumber function syntax has these parts:
Part Description
Required. Expression to be
Expression
formatted.
Optional. Numeric value
indicating how many places to
the right of the decimal are
NumDigitsAfterDecimal displayed. Default value is -1,
which indicates that the
computer's regional settings are
used.
Optional. Tristate constant that
indicates whether or not a
IncludeLeadingDigit leading zero is displayed for
fractional values. See Settings
section for values.
Optional. Tristate constant that
indicates whether or not to
UseParensForNegativeNumbers place negative values within
parentheses. See Settings
section for values.
Optional. Tristate constant that
indicates whether or not
numbers are grouped using the
GroupDigits
group delimiter specified in the
control panel. See Settings
section for values.
Settings
Remarks
When one or more of the optional arguments are omitted, the values for
omitted arguments are provided by the computer's regional settings.
Function FormatNumberDemo
Dim MyAngle, MySecant, MyNumber
MyAngle = 1.3 ' Define angle in radians.
MySecant = 1 / Cos(MyAngle) ' Calculate secant.
FormatNumberDemo = FormatNumber(MySecant
End Function
Microsoft® Visual Basic® Scripting Edition
Description
Syntax
FormatPercent(Expression[,NumDigitsAfterDecimal
[,IncludeLeadingDigit [,UseParensForNegativeNumbers [,GroupDigits]]]])
The FormatPercent function syntax has these parts:
Part Description
Required. Expression to be
Expression
formatted.
Optional. Numeric value
indicating how many places to
the right of the decimal are
NumDigitsAfterDecimal displayed. Default value is -1,
which indicates that the
computer's regional settings are
used.
Optional. Tristate constant that
indicates whether or not a
IncludeLeadingDigit leading zero is displayed for
fractional values. See Settings
section for values.
Optional. Tristate constant that
indicates whether or not to
UseParensForNegativeNumbers place negative values within
parentheses. See Settings
section for values.
Optional. Tristate constant that
indicates whether or not
numbers are grouped using the
GroupDigits
group delimiter specified in the
control panel. See Settings
section for values.
Settings
Remarks
When one or more optional arguments are omitted, the values for the
omitted arguments are provided by the computer's regional settings.
Description
Declares the name, arguments, and code that form the body of a
Function procedure.
Syntax
Part Description
Indicates that the Function procedure is accessible to all other procedures in all
Public
scripts.
Used only with the Public keyword in a Class block to indicate that the Function
Default procedure is the default method for the class. An error occurs if more than one Default
procedure is specified in a class.
Indicates that the Function procedure is accessible only to other procedures in the
Private script where it is declared or if the function is a member of a class, and that the
Function procedure is accessible only to other procedures in that class.
name Name of the Function; follows standard variable naming conventions.
List of variables representing arguments that are passed to the Function procedure
arglist
when it is called. Multiple variables are separated by commas.
statements Any group of statements to be executed within the body of the Function procedure.
expression Return value of the Function.
Remarks
Caution Function procedures can be recursive, that is, they can call themselves to perform a
given task. However, recursion can lead to stack overflow.
Function BinarySearch(. . .)
. . .
' Value not found. Return a value of False.
If lower > upper Then
BinarySearch = False
Exit Function
End If
. . .
End Function
Variables used in Function procedures fall into two categories:
those that are explicitly declared within the procedure and those
that are not. Variables that are explicitly declared in a procedure
(using Dim or the equivalent) are always local to the procedure.
Variables that are used but not explicitly declared in a procedure
are also local unless they are explicitly declared at some higher
level outside the procedure.
Caution 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. If
your procedure refers to an undeclared variable that has the same name as another procedure,
constant, or variable, it is assumed that your procedure is referring to that script-level name. To
avoid this kind of conflict, use an Option Explicit statement to force explicit declaration of
variables.
Caution VBScript may rearrange arithmetic expressions to increase internal efficiency. Avoid
using a Function procedure in an arithmetic expression when the function changes the value of
variables in the same expression.
Microsoft® Visual Basic® Scripting Edition
Description
Syntax
GetObject([pathname] [, class])
The GetObject function syntax has these parts:
Part Description
Optional; String. Full path and name of the file
pathname containing the object to retrieve. If pathname is
omitted, class is required.
class Optional; String. Class of the object.
The class argument uses the syntax appname.objectype and has these parts:
Part Description
Required; String. Name of the application providing
appname
the object.
objectype Required; String. Type or class of object to create.
Remarks
Use the GetObject function to access an Automation object from a file and
assign the object to an object variable. Use the Set statement to assign the
object returned by GetObject to the object variable. For example:
Dim CADObject
Set CADObject = GetObject("C:\CAD\SCHEMA.CAD"
When this code 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 (""), GetObject returns a new object
instance of the specified type. If the pathname argument is omitted,
GetObject returns a currently active object of the specified type. If no
object of the specified type exists, an error occurs.
Dim MyObject
Set MyObject = GetObject("C:\DRAWINGS\SAMPLE.DR
In the preceding example, FIGMENT is the name of a drawing application
and DRAWING is one of the object types it supports. Once an object is
activated, you reference it in code using the object variable you defined. In
the preceding example, you access properties and methods of the new
object using the object variable MyObject. For example:
MyObject.Line 9, 90
MyObject.InsertText 9, 100, "Hello, world."
MyObject.SaveAs "C:\DRAWINGS\SAMPLE.DRW"
Description
Syntax
Part Description
Required. Name of the object with which event is
object
associated.
Required. Name of the event to which the function is
event
to be bound.
Required. String containing the name of the Sub or
procname
Function procedure being associated with the event.
Remarks
Function GetRefTest()
Dim Splash
Splash = "GetRefTest Version 1.0" & vbCrLf
Splash = Splash & Chr(169) & " YourCompany 1999 "
MsgBox Splash
End Function
</SCRIPT>
Microsoft® Visual Basic® Scripting Edition Language Reference
Version 5
Global Property
See Also Applies To
Description
Syntax
Remarks
Description
Syntax
Hex(number)
The number argument is any valid expression.
Remarks
The following example uses the Hex function to return the hexadecimal value of a number:
Dim MyHex
MyHex = Hex(5) ' Returns 5.
MyHex = Hex(10) ' Returns A.
MyHex = Hex(459) ' Returns 1CB.
Microsoft® Visual Basic® Scripting Edition
Description
Syntax
object.HelpContext [= contextID]
The HelpContext property syntax has these parts:
Part Description
object Required. Always the Err object.
Optional. A valid identifier for a Help topic within the
contextID
Help file.
Remarks
Description
Syntax
object.HelpFile [= contextID]
The HelpFile property syntax has these parts:
Part Description
object Required. Always the Err object.
contextID Optional. Fully qualified path to the Help file.
Remarks
Description
Returns a whole number between 0 and 23, inclusive, representing the hour
of the day.
Syntax
Hour(time)
The time argument is any expression that can represent a time. If time contains Null, Null is returned.
The following example uses the Hour function to obtain the hour from the current time:
Syntax
If condition Then
[statements]
[ElseIf condition-n Then
[elseifstatements]] . . .
[Else
[elsestatements]]
End If
Part Description
One or more of the following two types of expressions:
A numeric or string expression that evaluates to True or False. If
condition is Null, condition is treated as False.
condition An expression of the form TypeOf objectname Is objecttype. The
objectname is any object reference and objecttype is any valid object
type. The expression is True if objectname is of the object type
specified by objecttype; otherwise it is False.
You can use the single-line form (first syntax) for short, simple tests.
However, the block form (second syntax) provides more structure and
flexibility than the single-line form and is usually easier to read, maintain,
and debug.
If A > 10 Then A = A + 1 : B = B + A : C = C + B
When executing a block If (second syntax), condition is tested. If condition is True, the statements
following Then are executed. If condition is False, each ElseIf (if any) is evaluated in turn. When a
True condition is found, the statements following the associated Then are executed. If none of the
ElseIf statements are True (or there are no ElseIf clauses), the statements following Else are
executed. After executing the statements following Then or Else, execution continues with the
statement following End If.
The Else and ElseIf clauses are both optional. You can have as many ElseIf statements as you want
in a block If, but none can appear after the Else clause. Block If statements can be nested; that is,
contained within one another.
What follows the Then keyword is examined to determine whether or not a statement is a block If. If
anything other than a comment appears after Then on the same line, the statement is treated as a
single-line If statement.
A block If statement must be the first statement on a line. The block If must end with an End If
statement.
Microsoft® Visual Basic® Scripting Edition
Property
See Also Applies To
Description
Syntax
Remarks
Description
Syntax
Part Description
result Any numeric variable.
expression1 Any expression.
expression2 Any expression.
Remarks
If bit in expression1
And bit in expression2 is Then result is
is
0 0 1
0 1 1
1 0 0
1 1 1
Microsoft® Visual Basic® Scripting Edition
Language Reference
Initialize Event Version 5
Description
Syntax
Remarks
Class TestClass
Private Sub Class_Initialize ' Setup Initialize event.
MsgBox("TestClass started")
End Sub
Private Sub Class_Terminate ' Setup Terminate event.
MsgBox("TestClass terminated")
End Sub
End Class
See Also
Description
Displays a prompt in a dialog box, waits for the user to input text or click a
button, and returns the contents of the text box.
Syntax
Part Description
String expression displayed as the message in the dialog
box. The maximum length of prompt is approximately
1024 characters, depending on the width of the
characters used. If prompt consists of more than one
prompt
line, you can separate the lines using a carriage return
character (Chr(13)), a linefeed character (Chr(10)), or
carriage return–linefeed character combination
(Chr(13) & Chr(10)) between each line.
String expression displayed in the title bar of the dialog
title box. If you omit title, the application name is placed in
the title bar.
String expression displayed in the text box as the default
default response if no other input is provided. If you omit
default, the text box is displayed empty.
Numeric expression that specifies, in twips, the
horizontal distance of the left edge of the dialog box
xpos
from the left edge of the screen. If xpos is omitted, the
dialog box is horizontally centered.
Numeric expression that specifies, in twips, the vertical
distance of the upper edge of the dialog box from the
ypos top of the screen. If ypos is omitted, the dialog box is
vertically positioned approximately one-third of the way
down the screen.
String expression that identifies the Help file to use to
helpfile provide context-sensitive Help for the dialog box. If
helpfile is provided, context must also be provided.
Numeric expression that identifies the Help context
number assigned by the Help author to the appropriate
context
Help topic. If context is provided, helpfile must also be
provided.
Remarks
When both helpfile and context are supplied, a Help button is automatically
added to the dialog box.
If the user clicks OK or presses ENTER, the InputBox function returns whatever is in the text box.
If the user clicks Cancel, the function returns a zero-length string ("").
The following example uses the InputBox function to display an input box and assign the string to
the variable Input:
Dim Input
Input = InputBox("Enter your name")
MsgBox ("You entered: " & Input)
Microsoft® Visual Basic® Scripting Edition InStr Language Reference
Version 1
Function
See Also
Description
Returns the position of the first occurrence of one string within another.
Syntax
Part Description
Optional. Numeric expression that sets the starting
position for each search. If omitted, search begins at
start the first character position. If start contains Null, an
error occurs. The start argument is required if compare
is specified.
string1 Required. String expression being searched.
string2 Required. String expression searched for.
Optional. Numeric value indicating the kind of
comparison to use when evaluating substrings. See
compare
Settings section for values. If omitted, a binary
comparison is performed.
Settings
Return Values
If InStr returns
string1 is zero-length 0
string1 is Null Null
string2 is zero-length start
string2 is Null Null
string2 is not found 0
string2 is found within string1 Position at which match is found
start > Len(string2) 0
Remarks
Description
Syntax
result = number1\number2
Part Description
result Any numeric variable.
number1 Any numeric expression.
number2 Any numeric expression.
Remarks
If any expression is Null, result is also Null. Any expression that is Empty
is treated as 0.
Microsoft® Visual Basic® Scripting Edition Is Language Reference
Version 1
Operator
See Also
Description
Syntax
Part Description
result Any numeric variable.
object1 Any object name.
object2 Any object name.
Remarks
If object1 and object2 both refer to the same object, result is True; if they
do not, result is False. Two variables can be made to refer to the same
object in several ways.
In the following example, A has been set to refer to the same object as B:
Set A = B
The following example makes A and B refer to the same object as C:
Set A = C
Set B = C
Microsoft® Visual Basic® Scripting Edition IsArray Language Reference
Version 1
Function
See Also
Description
Syntax
IsArray(varname)
Remarks
Dim MyVariable
Dim MyArray(3)
MyArray(0) = "Sunday"
MyArray(1) = "Monday"
MyArray(2) = "Tuesday"
MyVariable = IsArray(MyArray) ' MyVariable contains "Tr
Microsoft® Visual Basic® Scripting Edition IsDate Language Reference
Version 1
Function
See Also
Description
Syntax
IsDate(expression)
The expression argument can be any date expression or string expression recognizable as a date or
time.
Remarks
See Also
Description
Syntax
IsEmpty(expression)
Remarks
Description
Syntax
IsNull(expression)
The expression argument can be any expression.
Remarks
IsNull returns True if expression is Null, that is, it contains no valid data;
otherwise, IsNull returns False. If expression consists of more than one
variable, Null in any constituent variable causes True to be returned for the
entire expression.
The Null value indicates that the variable contains no valid data. Null is not the same as Empty,
which indicates that a variable has not yet been initialized. It is also not the same as a zero-length
string (""), which is sometimes referred to as a null string.
The following example uses the IsNull function to determine whether a variable contains a Null:
Dim MyVar, MyCheck
MyCheck = IsNull(MyVar) ' Returns False.
MyVar = Null ' Assign Null.
MyCheck = IsNull(MyVar) ' Returns True.
MyVar = Empty ' Assign Empty.
MyCheck = IsNull(MyVar) ' Returns False.
Microsoft® Visual Basic® Scripting Edition
Description
Syntax
IsNumeric(expression)
The expression argument can be any expression.
Remarks
See Also
Description
Syntax
IsObject(expression)
The expression argument can be any expression.
Remarks
Description
Syntax
Join(list[, delimiter])
The Join function syntax has these parts:
Part Description
Required. One-dimensional array containing
list
substrings to be joined.
Optional. String character used to separate the
substrings in the returned string. If omitted, the space
delimiter character (" ") is used. If delimiter is a zero-length
string, all items in the list are concatenated with no
delimiters.
Remarks
The following example uses the Join function to join the substrings of
MyArray:
Dim MyString
Dim MyArray(4)
MyArray(0) = "Mr."
MyArray(1) = "John "
MyArray(2) = "Doe "
MyArray(3) = "III"
MyString = Join(MyArray) ' MyString contains "Mr. John
Microsoft® Visual Basic® Scripting Edition LBound Language Reference
Version 1
Function
See Also
Description
Syntax
LBound(arrayname[, dimension])
The LBound function syntax has these parts:
Part Description
Name of the array variable; follows standard
arrayname
variable naming conventions.
Whole number indicating which dimension's lower
bound is returned. Use 1 for the first dimension, 2
dimension
for the second, and so on. If dimension is omitted, 1
is assumed.
Remarks
The LBound function is used with the UBound function to determine the
size of an array. Use the UBound function to find the upper limit of an
array dimension.
The lower bound for any dimension is always 0.
Microsoft® Visual Basic® Scripting Edition LCase Language Reference
Version 1
Function
See Also
Description
Syntax
LCase(string)
The string argument is any valid string expression. If string contains Null, Null is returned.
Remarks
Only uppercase letters are converted to lowercase; all lowercase letters and
nonletter characters remain unchanged.
Dim MyString
Dim LCaseString
MyString = "VBSCript"
LCaseString = LCase(MyString) ' LCaseString contains "vbscript".
Microsoft® Visual Basic® Scripting Edition Left Language Reference
Version 1
Function
See Also
Description
Syntax
Left(string, length)
The Left function syntax has these arguments:
Part Description
String expression from which the leftmost characters are
string
returned. If string contains Null, Null is returned.
Numeric expression indicating how many characters to
return. If 0, a zero-length string("") is returned. If greater
length
than or equal to the number of characters in string, the
entire string is returned.
Remarks
Description
Syntax
Len(string | varname)
The Len function syntax has these parts:
Part Description
Any valid string expression. If string contains Null,
string
Null is returned.
Any valid variable name. If varname contains Null,
varname
Null is returned.
Remarks
The following example uses the Len function to return the number of
characters in a string:
Dim MyString
MyString = Len("VBSCRIPT") ' MyString contains 8.
Note The LenB function is used with byte data contained in a string. Instead of
returning the number of characters in a string, LenB returns the number of bytes used
to represent that string.
Microsoft® Visual Basic® Scripting Edition Language Reference
Version 5
Length Property
See Also Applies To
Description
Syntax
object.Length
Remarks
Syntax
LoadPicture(picturename)
Remarks
Description
Syntax
Log(number)
The number argument can be any valid numeric expression greater than 0.
Remarks
Function Log10(X)
Log10 = Log(X) / Log(10)
End Function
LTrim,
Microsoft® Visual Basic® Scripting Edition
Language Reference
RTrim, and Trim Version 1
Functions
See Also
Description
Syntax
LTrim(string)
RTrim(string)
Trim(string)
The string argument is any valid string expression. If string contains Null,
Null is returned.
Remarks
The following example uses the LTrim, RTrim, and Trim functions to trim
leading spaces, trailing spaces, and both leading and trailing spaces,
respectively:
Dim MyVar
MyVar = LTrim(" vbscript ") ' MyVar contains "vbscript ".
MyVar = RTrim(" vbscript ") ' MyVar contains " vbscript"
MyVar = Trim(" vbscript ") ' MyVar contains "vbscript".
Microsoft® Visual Basic® Scripting Edition Match Language Reference
Version 5
Object
See Also Properties
Description
Remarks
Description
Remarks
Description
Syntax
Part Description
String expression from which characters are returned. If
string
string contains Null, Null is returned.
Character position in string at which the part to be taken
start begins. If start is greater than the number of characters in
string, Mid returns a zero-length string ("").
Number of characters to return. If omitted or if there are
fewer than length characters in the text (including the
length
character at start), all characters from the start position to
the end of the string are returned.
Remarks
The following example uses the Mid function to return six characters,
beginning with the fourth character, in a string:
Dim MyVar
MyVar = Mid("VB Script is fun!", 4, 6) ' MyVar contains "S
Description
Syntax
Minute(time)
The time argument is any expression that can represent a time. If time contains Null, Null is returned.
Remarks
The following example uses the Minute function to return the minute of the
hour:
Dim MyVar
MyVar = Minute(Now)
Microsoft® Visual Basic® Scripting Edition
Since this constant is built into VBScript, you don't have to define it before using
it. Use it anywhere in your code to represent the values shown.
Description
Syntax
Part Description
result Any numeric variable.
number1 Any numeric expression.
number2 Any numeric expression.
Remarks
A = 19 Mod 6.7
If any expression is Null, result is also Null. Any expression that is Empty
is treated as 0.
Microsoft® Visual Basic® Scripting Edition Month Language Reference
Version 1
Function
See Also
Description
Syntax
Month(date)
The date argument is any expression that can represent a date. If date contains Null, Null is returned.
Remarks
The following example uses the Month function to return the current
month:
Dim MyVar
MyVar = Month(Now) ' MyVar contains the number corresponding to
' the current month.
Microsoft® Visual Basic® Scripting Edition
Description
Syntax
MonthName(month[, abbreviate])
The MonthName function syntax has these parts:
Part Description
Required. The numeric designation of the month. For
month
example, January is 1, February is 2, and so on.
Optional. Boolean value that indicates if the month
name is to be abbreviated. If omitted, the default is
abbreviate
False, which means that the month name is not
abbreviated.
Remarks
Dim MyVar
MyVar = MonthName(10, True) ' MyVar contains "Oct".
Microsoft® Visual Basic® Scripting Edition MsgBox Language Reference
Version 2
Constants
See Also
The following constants are used with the MsgBox function to identify what
buttons and icons appear on a message box and which button is the default. In
addition, the modality of the MsgBox can be specified. Since these constants are
built into VBScript, you don't have to define them before using them. Use them
anywhere in your code to represent the values shown for each.
The following constants are used with the MsgBox function to identify
which button a user has selected. These constants are only available when
your project has an explicit reference to the appropriate type library
containing these constant definitions. For VBScript, you must explicitly
declare these constants in your code.
Description
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.
Syntax
Part Description
String expression displayed as the message in the dialog
box. The maximum length of prompt is approximately
1024 characters, depending on the width of the
characters used. If prompt consists of more than one
prompt
line, you can separate the lines using a carriage return
character (Chr(13)), a linefeed character (Chr(10)), or
carriage return–linefeed character combination
(Chr(13) & Chr(10)) between each line.
Numeric expression that is the sum of values specifying
the number and type of buttons to display, the icon style
buttons to use, the identity of the default button, and the
modality of the message box. See Settings section for
values. If omitted, the default value for buttons is 0.
String expression displayed in the title bar of the dialog
title box. If you omit title, the application name is placed in
the title bar.
String expression that identifies the Help file to use to
helpfile provide context-sensitive Help for the dialog box. If
helpfile is provided, context must also be provided. Not
available on 16-bit platforms.
Numeric expression that identifies the Help context
number assigned by the Help author to the appropriate
context
Help topic. If context is provided, helpfile must also be
provided. Not available on 16-bit platforms.
Settings
Return Values
Remarks
When both helpfile and context are provided, the user can press F1 to view
the Help topic corresponding to the context.
If the dialog box displays a Cancel button, pressing the ESC key has the same effect as clicking
Cancel. If the dialog box contains a Help button, context-sensitive Help is provided for the dialog
box. However, no value is returned until one of the other buttons is clicked.
When the MsgBox function is used with Microsoft Internet Explorer, the title of any dialog presented
always contains "VBScript:" to differentiate it from standard system dialogs.
The following example uses the MsgBox function to display a message box and return a value
describing which button was clicked:
Dim MyVar
MyVar = MsgBox ("Hello World!", 65, "MsgBox Example") ' MyVar contain
' depending on which button is
' clicked.
Microsoft® Visual Basic® Scripting Edition * Language Reference
Version 1
Operator
See Also
Description
Syntax
result = number1*number2
The * operator syntax has these parts:
Part Description
result Any numeric variable.
number1 Any numeric expression.
number2 Any numeric expression.
Remarks
Description
Finds the difference between two numbers or indicates the negative value of
a numeric expression.
Syntax 1
result = number1-number2
Syntax 2
-number
The - operator syntax has these parts:
Part Description
result Any numeric variable.
number Any numeric expression.
number1 Any numeric expression.
number2 Any numeric expression.
Remarks
Description
Syntax
Part Description
result Any numeric variable.
expression Any expression.
Remarks
Description
Returns the current date and time according to the setting of your
computer's system date and time.
Syntax
Now
Remarks
The following example uses the Now function to return the current date and
time:
Dim MyVar
MyVar = Now ' MyVar contains the current date and time.
Language Reference
Microsoft® Visual Basic® Scripting Edition Nothing Version 1
See Also
Description
See Also
Description
The Null keyword is used to indicate that a variable contains no valid data.
This is not the same thing as Empty.
Microsoft® Visual Basic® Scripting Edition Number Language Reference
Version 1
Property
See Also Applies to
Description
Syntax
object.Number [= errornumber]
The Number property syntax has these parts:
Part Description
object Always the Err object.
An integer representing a VBScript error number
errornumber
or an SCODE error value.
Remarks
Description
Syntax
Oct(number)
The number argument is any valid expression.
Remarks
The following example uses the Oct function to return the octal value of a number:
Dim MyOct
MyOct = Oct(4) ' Returns 4.
MyOct = Oct(8) ' Returns 10.
MyOct = Oct(459) ' Returns 713.
On
Microsoft® Visual Basic® Scripting Edition Language Reference
Version 1
Error Statement
See Also
Description
Syntax
Remarks
On Error Resume Next causes execution to continue with the statement immediately following the
statement that caused the run-time error, or with the statement immediately following the most recent
call out of the procedure containing the On Error Resume Next statement. This allows execution to
continue despite a run-time error. You can then build the error-handling routine inline within the
procedure.
An On Error Resume Next statement becomes inactive when another procedure is called, so you
should execute an On Error Resume Next statement in each called routine if you want inline error
handling within that routine. When a procedure is exited, the error-handling capability reverts to
whatever error-handling was in place before entering the exited procedure.
Use On Error GoTo 0 to disable error handling if you have previously enabled it using On Error
Resume Next.
The following example illustrates use of the On Error Resume Next statement:
Description
The string concatenation operator (&) is not an arithmetic operator, but in precedence it does fall
after all arithmetic operators and before all comparison operators. The Is operator is an object
reference comparison operator. It does not compare objects or their values; it checks only to
determine if two object references refer to the same object.
Option
Microsoft® Visual Basic® Scripting Edition Language Reference
Version 1
Explicit Statement
Description
Syntax
Option Explicit
Remarks
If used, the Option Explicit statement must appear in a script before any
other statements.
When you use the Option Explicit statement, you must explicitly declare
all variables using the Dim, Private, Public, or ReDim statements. If you
attempt to use an undeclared variable name, an error occurs.
Description
Syntax
Part Description
result Any numeric variable.
expression1 Any expression.
expression2 Any expression.
Remarks
If bit in expression1
And bit in expression2 is Then result is
is
0 0 0
0 1 1
1 0 1
1 1 1
Microsoft® Visual Basic® Scripting Edition Pattern Language Reference
Version 5
Property
See Also Applies to
Description
Syntax
object.Pattern [= "searchstring"]
Part Description
object Required. Always a RegExp object variable.
Optional. Regular string expression being searched for. May include any of the
searchstring
regular expression characters defined in the table in the Settings section.
Settings
Character Description
Marks the next character as either a special character or a literal. For example, "n"
\ matches the character "n". "\n" matches a newline character. The sequence "\\"
matches "\" and "\(" matches "(".
^ Matches the beginning of input.
$ Matches the end of input.
Matches the preceding character zero or more times. For example, "zo*" matches
*
either "z" or "zoo".
Matches the preceding character one or more times. For example, "zo+" matches "zoo"
+
but not "z".
Matches the preceding character zero or one time. For example, "a?ve?" matches the
?
"ve" in "never".
. Matches any single character except a newline character.
Matches pattern and remembers the match. The matched substring can be retrieved
(pattern) from the resulting Matches collection, using Item [0]...[n]. To match parentheses
characters ( ), use "\(" or "\)".
Matches either x or y. For example, "z|food" matches "z" or "food". "(z|f)oo" matches
x|y
"zoo" or "food".
n is a nonnegative integer. Matches exactly n times. For example, "o{2}" does not
{n}
match the "o" in "Bob," but matches the first two o's in "foooood".
n is a nonnegative integer. Matches at least n times. For example, "o{2,}" does not
{n,} match the "o" in "Bob" and matches all the o's in "foooood." "o{1,}" is equivalent to
"o+". "o{0,}" is equivalent to "o*".
m and n are nonnegative integers. Matches at least n and at most m times. For
{n,m} example, "o{1,3}" matches the first three o's in "fooooood." "o{0,1}" is equivalent to
"o?".
A character set. Matches any one of the enclosed characters. For example, "[abc]"
[xyz]
matches the "a" in "plain".
A negative character set. Matches any character not enclosed. For example, "[^abc]"
[^xyz]
matches the "p" in "plain".
A range of characters. Matches any character in the specified range. For example, "[a-
[a-z]
z]" matches any lowercase alphabetic character in the range "a" through "z".
A negative range characters. Matches any character not in the specified range. For
[^m-z]
example, "[m-z]" matches any character not in the range "m" through "z".
Matches a word boundary, that is, the position between a word and a space. For
\b
example, "er\b" matches the "er" in "never" but not the "er" in "verb".
\B Matches a nonword boundary. "ea*r\B" matches the "ear" in "never early".
\d Matches a digit character. Equivalent to [0-9].
\D Matches a nondigit character. Equivalent to [^0-9].
\f Matches a form-feed character.
\n Matches a newline character.
\r Matches a carriage return character.
Matches any white space including space, tab, form-feed, etc. Equivalent to "
\s
[ \f\n\r\t\v]".
\S Matches any nonwhite space character. Equivalent to "[^ \f\n\r\t\v]".
\t Matches a tab character.
\v Matches a vertical tab character.
\w Matches any word character including underscore. Equivalent to "[A-Za-z0-9_]".
\W Matches any nonword character. Equivalent to "[^A-Za-z0-9_]".
Matches num, where num is a positive integer. A reference back to remembered
\num
matches. For example, "(.)\1" matches two consecutive identical characters.
Matches n, where n is an octal escape value. Octal escape values must be 1, 2, or 3
digits long. For example, "\11" and "\011" both match a tab character. "\0011" is the
\n equivalent of "\001" & "1". Octal escape values must not exceed 256. If they do, only
the first two digits comprise the expression. Allows ASCII codes to be used in regular
expressions.
Matches n, where n is a hexadecimal escape value. Hexadecimal escape values must
\xn be exactly two digits long. For example, "\x41" matches "A". "\x041" is equivalent to
"\x04" & "1". Allows ASCII codes to be used in regular expressions.
Remarks
Description
Syntax
Part Description
varname Name of the variable; follows standard variable naming conventions.
Dimensions of an array variable; up to 60 multiple dimensions may be declared. The
subscripts argument uses the following syntax:
Remarks
You can also use the Private statement with empty parentheses
to declare a dynamic array. After declaring a dynamic array, use
the ReDim statement within a procedure to define the number of
dimensions and elements in the array. If you try to redeclare a
dimension for an array variable whose size was explicitly
specified in a Private, Public, or Dim statement, an error occurs.
Tip When you use the Private statement in a procedure, you generally put the Private statement
at the beginning of the procedure.
Description
Syntax
Part Description
Indicates that the Property Get procedure is accessible to all other procedures in all
Public
scripts.
Used only with the Public keyword to indicate that the property defined in the
Default
Property Get procedure is the default property for the class.
Indicates that the Property Get procedure is accessible only to other procedures in the
Private
Class block where it's declared.
Name of the Property Get procedure; follows standard variable naming conventions,
name except that the name can be the same as a Property Let or Property Set procedure in
the same Class block.
List of variables representing arguments that are passed to the Property Get procedure
arglist when it is called. Multiple arguments are separated by commas. The name of each
argument in a Property Get procedure must be the same as the corresponding
argument in a Property Let procedure (if one exists).
Any group of statements to be executed within the body of the Property Get
statements
procedure.
Keyword used when assigning an object as the return value of a Property Get
Set
procedure.
expression Return value of the Property Get procedure.
Remarks
Description
Syntax
Part Description
Indicates that the Property Let procedure is accessible to all other procedures in all
Public
scripts.
Indicates that the Property Let procedure is accessible only to other procedures in the
Private
Class block where it's declared.
Name of the Property Let procedure; follows standard variable naming conventions,
name except that the name can be the same as a Property Get or Property Set procedure in
the same Class block.
List of variables representing arguments that are passed to the Property Let procedure
when it is called. Multiple arguments are separated by commas. The name of each
argument in a Property Let procedure must be the same as the corresponding
arglist
argument in a Property Get procedure. In addition, the Property Let procedure will
always have one more argument than its corresponding Property Get procedure. That
argument is the value being assigned to the property.
value Variable to contain the value to be assigned to the property. When the procedure is
called, this argument appears on the right side of the calling expression.
Any group of statements to be executed within the body of the Property Let
statements
procedure.
NoteVersion Version Every Property Let statement must define at least one argument for the
procedure it defines. That argument (or the last argument if there is more than one) contains the
actual value to be assigned to the property when the procedure defined by the Property Let
statement is invoked. That argument is referred to as value in the preceding syntax.
Remarks
Description
Syntax
Part Description
Indicates that the Property Set procedure is accessible to all other procedures in all
Public
scripts.
Indicates that the Property Set procedure is accessible only to other procedures in the
Private
Class block where it's declared.
Name of the Property Set procedure; follows standard variable naming conventions,
name except that the name can be the same as a Property Get or Property Let procedure in
the same Class block.
List of variables representing arguments that are passed to the Property Set procedure
when it is called. Multiple arguments are separated by commas. In addition, the
arglist
Property Set procedure will always have one more argument than its corresponding
Property Get procedure. That argument is the object being assigned to the property.
Variable containing the object reference used on the right side of the object reference
reference assignment.
Any group of statements to be executed within the body of the Property Set
statements
procedure.
NoteVersion Version Every Property Set statement must define at least one argument for the
procedure it defines. That argument (or the last argument if there is more than one) contains the
actual object reference for the property when the procedure defined by the Property Set statement
is invoked. That argument is referred to as reference in the preceding syntax.
Remarks
Description
Syntax
Part Description
varname Name of the variable; follows standard variable naming conventions.
Dimensions of an array variable; up to 60 multiple dimensions may be declared. The
subscripts argument uses the following syntax:
Remarks
You can also use the Public statement with empty parentheses to
declare a dynamic array. After declaring a dynamic array, use the
ReDim statement within a procedure to define the number of
dimensions and elements in the array. If you try to redeclare a
dimension for an array variable whose size was explicitly
specified in a Private, Public, or Dim statement, an error occurs.
Description
Syntax
Part Description
object Always the Err object.
A Long integer subtype that identifies the nature of
number the error. VBScript errors (both VBScript-defined
and user-defined errors) are in the range 0–65535.
A string expression naming the object or application
that originally generated the error. When setting this
property for an Automation object, use the form
source
project.class. If nothing is specified, the
programmatic ID of the current VBScript project is
used.
A string expression describing the error. If
unspecified, the value in number is examined. If it
can be mapped to a VBScript run-time error code, a
description
string provided by VBScript is used as description.
If there is no VBScript error corresponding to
number, a generic error message is used.
The fully qualified path to the Help file in which
help on this error can be found. If unspecified,
helpfile VBScript uses the fully qualified drive, path, and
file name of the VBScript Help file.
Remarks
All the arguments are optional except number. If you use Raise, however,
without specifying some 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. For example, to generate the error number 1050,
assign vbObjectError + 1050 to the number property.
Description
Syntax
Randomize [number]
The number argument can be any valid numeric expression.
Remarks
Description
Syntax
Part Description
Preserves the data in an existing array when you
Preserve
change the size of the last dimension.
Name of the variable; follows standard variable
varname
naming conventions.
Dimensions of an array variable; up to 60 multiple
dimensions may be declared. The subscripts
argument uses the following syntax:
subscripts
upper [,upper] . . .
Remarks
The ReDim statement is used to size or resize a dynamic array that has
already been formally declared using a Private, Public, or Dim statement
with empty parentheses (without dimension subscripts). You can use the
ReDim statement repeatedly to change the number of elements and
dimensions in an array.
If you use the Preserve keyword, you can resize only the last array dimension, and you can't change
the number of dimensions at all. For example, if your array has only one dimension, you can resize
that dimension because it is the last and only dimension. However, if your array has two or more
dimensions, you can change the size of only the last dimension and still preserve the contents of the
array.
The following example shows how you can increase the size of the last dimension of a dynamic array
without erasing any existing data contained in the array.
When variables are initialized, a numeric variable is initialized to 0 and a string variable is initialized
to a zero-length string (""). A variable that refers to an object 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.
Microsoft® Visual Basic® Scripting Edition RegExp Language Reference
Version 5
Object
See Also Methods Properties
Description
Remarks
Syntax
Rem comment
or
' comment
The comment argument is the text of any comment you want to include. After the Rem keyword, a
space is required before comment.
Remarks
As shown in the syntax section, you can use an apostrophe (') instead of the Rem keyword. If the Rem
keyword follows other statements on a line, it must be separated from the statements by a colon.
However, when you use an apostrophe, the colon is not required after other statements.
Description
Syntax
Part Description
Required. String expression containing substring to
expression
replace.
find Required. Substring being searched for.
replacewith Required. Replacement substring.
Optional. Position within expression where
start substring search is to begin. If omitted, 1 is
assumed. Must be used in conjunction with count.
Optional. Number of substring substitutions to
perform. If omitted, the default value is -1, which
count
means make all possible substitutions. Must be used
in conjunction with start.
Optional. Numeric value indicating the kind of
comparison to use when evaluating substrings. See
compare Settings section for values. If omitted, the default
value is 0, which means perform a binary
comparison.
Settings
Return Values
If Replace returns
expression is zero-
Zero-length string ("").
length
expression is Null An error.
find is zero-length Copy of expression.
replacewith is zero- Copy of expression with all occurences of
length find removed.
start >
Zero-length string.
Len(expression)
count is 0 Copy of expression.
Remarks
Dim MyString
MyString = Replace("XXpXXPXXp", "p", "Y") ' A binary
' of the string. Returns "X
MyString = Replace("XXpXXPXXp", "p", "Y", ' A textua
' Returns "YXXYXXY".
Microsoft® Visual Basic® Scripting Edition Language Reference
Version 5
Replace Method
See Also Applies to
Description
Syntax
object.Replace(string1, string2)
Part Description
object Required. Always the name of a RegExp object.
string1 Required. String1 is the text string in which the text replacement is to occur.
string2 Required. String2 is the replacement text string.
Remarks
The actual pattern for the text being replaced is set using the
Pattern property of the RegExp object.
Syntax
Part Description
Required. Number in the range 0-255 representing the red
red
component of the color.
Required. Number in the range 0-255 representing the
green
green component of the color.
Required. Number in the range 0-255 representing the
blue
blue component of the color.
Remarks
The low-order byte contains the value for red, the middle byte contains the
value for green, and the high-order byte contains the value for blue.
For applications that require the byte order to be reversed, the following
function will provide the same information with the bytes reversed:
Description
Syntax
Right(string, length)
The Right function syntax has these arguments:
Part Description
String expression from which the rightmost characters are
string
returned. If string contains Null, Null is returned.
Numeric expression indicating how many characters to
return. If 0, a zero-length string is returned. If greater
length
than or equal to the number of characters in string, the
entire string is returned.
Remarks
Description
Syntax
Rnd[(number)]
The number argument can be any valid numeric expression.
Remarks
The Rnd function returns a value less than 1 but greater than or equal to 0.
The value of number determines how Rnd generates a random number:
Before calling Rnd, use the Randomize statement without an argument to initialize the random-
number generator with a seed based on the system timer.
Description
Syntax
Round(expression[, numdecimalplaces])
The Round function syntax has these parts:
Part Description
Required. Numeric expression being
expression
rounded.
Optional. Number indicating how many
places to the right of the decimal are
numdecimalplaces
included in the rounding. If omitted, integers
are returned by the Round function.
Remarks
The following example uses the Round function to round a number to two
decimal places:
Dim MyVar, pi
pi = 3.14159
MyVar = Round(pi, 2) ' MyVar contains 3.14.
Microsoft® Visual Basic® Scripting Edition
Description
Syntax
ScriptEngine
Return Values
String Description
Indicates that Microsoft® Visual Basic® Scripting
VBScript
Edition is the current scripting engine.
Indicates that Microsoft JScript® is the current
JScript
scripting engine.
Indicates that Microsoft Visual Basic for Applications
VBA
is the current scripting engine.
Remarks
Function GetScriptEngineInfo
Dim s
s = "" ' Build string with necessary info.
s = ScriptEngine & " Version "
s = s & ScriptEngineMajorVersion & "."
s = s & ScriptEngineMinorVersion & "."
s = s & ScriptEngineBuildVersion
GetScriptEngineInfo = s ' Return the results.
End Function
Microsoft® Visual Basic® Scripting Edition
Description
Syntax
ScriptEngineBuildVersion
Remarks
Function GetScriptEngineInfo
Dim s
s = "" ' Build string with necessary info.
s = ScriptEngine & " Version "
s = s & ScriptEngineMajorVersion & "."
s = s & ScriptEngineMinorVersion & "."
s = s & ScriptEngineBuildVersion
GetScriptEngineInfo = s ' Return the results.
End Function
Microsoft® Visual Basic® Scripting Edition
Description
Syntax
ScriptEngineMajorVersion
Remarks
Function GetScriptEngineInfo
Dim s
s = "" ' Build string with necessary info.
s = ScriptEngine & " Version "
s = s & ScriptEngineMajorVersion & "."
s = s & ScriptEngineMinorVersion & "."
s = s & ScriptEngineBuildVersion
GetScriptEngineInfo = s ' Return the results.
End Function
Microsoft® Visual Basic® Scripting Edition
Description
Syntax
ScriptEngineMinorVersion
Remarks
Function GetScriptEngineInfo
Dim s
s = "" ' Build string with necessary info.
s = ScriptEngine & " Version "
s = s & ScriptEngineMajorVersion & "."
s = s & ScriptEngineMinorVersion & "."
s = s & ScriptEngineBuildVersion
GetScriptEngineInfo = s ' Return the results.
End Function
Microsoft® Visual Basic® Scripting Edition Second Language Reference
Version 1
Function
See Also
Description
Syntax
Second(time)
The time argument is any expression that can represent a time. If time contains Null, Null is returned.
Remarks
The following example uses the Second function to return the current
second:
Dim MySec
MySec = Second(Now) ' MySec contains the number representing
' the current second.
Select
Microsoft® Visual Basic® Scripting Edition Language Reference
Version 1
Case Statement
See Also
Description
Syntax
Part Description
testexpression Any numeric or string expression.
expressionlist- Required if Case appears. Delimited list of one
n or more expressions.
One or more statements executed if
statements-n testexpression matches any part of
expressionlist-n.
One or more statements executed if
elsestatements-
testexpression doesn't match any of the Case
n
clauses.
Remarks
If testexpression matches any Case expressionlist expression, the statements
following that Case clause are executed up to the next Case clause, or for
the last clause, up to End Select. Control then passes to the statement
following End Select. If testexpression matches an expressionlist
expression in more than one Case clause, only the statements following the
first match are executed.
The Case Else clause is used to indicate the elsestatements to be executed if no match is found
between the testexpression and an expressionlist in any of the other Case selections. Although not
required, it is a good idea to have a Case Else statement in your Select Case block to handle
unforeseen testexpression values. If no Case expressionlist matches testexpression and there is no
Case Else statement, execution continues at the statement following End Select.
Select Case statements can be nested. Each nested Select Case statement must have a matching End
Select statement.
The following example illustrates the use of the Select Case statement:
Description
Syntax 1
Syntax 2
Remarks
Function ShowFreeSpace(drvPath)
Dim fso, d, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set d = fso.GetDrive(fso.GetDriveName(drvPath))
s = "Drive " & UCase(drvPath) & " - "
s = s & d.VolumeName & "<BR>"
s = s & "Free Space: " & FormatNumber(d.FreeSpace/1024, 0)
s = s & " Kbytes"
ShowFreeSpace = s
End Function
Description
Syntax
Sgn(number)
The number argument can be any valid numeric expression.
Return Values
Remarks
The sign of the number argument determines the return value of the Sgn
function.
The following example uses the Sgn function to determine the sign of a number:
Description
Syntax
Sin(number)
The number argument can be any valid numeric expression that expresses an angle in radians.
Remarks
The Sin function takes an angle and returns the ratio of two sides of a right
triangle. The ratio is the length of the side opposite the angle divided by the
length of the hypotenuse. The result lies in the range -1 to 1.
To convert degrees to radians, multiply degrees by pi/180. To convert radians to degrees, multiply
radians by 180/pi.
The following example uses the Sin function to return the sine of an angle:
Description
Syntax
object.Source [= stringexpression]
The Source property syntax has these parts:
Part Description
object Always the Err object.
A string expression representing the application
stringexpression
that generated the error.
Remarks
The Source property specifies a string expression that is usually the class
name or programmatic ID of the object that caused the error. Use Source to
provide your users with information when your code is unable to handle an
error generated in an accessed object. For example, if you access Microsoft
Excel and it generates a Division by zero error, Microsoft Excel sets
Err.Number to its error code for that error and sets Source to
Excel.Application. Note that if the error is generated in another object
called by Microsoft Excel, Excel intercepts the error and sets Err.Number
to its own code for Division by zero. However, it leaves the other Err object
(including Source) as set by the object that generated the error.
Source always contains the name of the object that originally generated the error — your code can
try to handle the error according to the error documentation of the object you accessed. If your error
handler fails, you can use the Err object information to describe the error to your user, using Source
and the other Err to inform the user which object originally caused the error, its description of the
error, and so forth.
When generating an error from code, Source is your application's programmatic ID.
Description
Syntax
Space(number)
The number argument is the number of spaces you want in the string.
Remarks
The following example uses the Space function to return a string consisting
of a specified number of spaces:
Dim MyString
MyString = Space(10) ' Returns a string with 10 spaces.
MyString = "Hello" & Space(10) & "World" ' Insert 10 spaces between two st
Microsoft® Visual Basic® Scripting Edition Split Language Reference
Version 2
Function
See Also
Description
Syntax
Part Description
Required. String expression containing substrings
and delimiters. If expression is a zero-length string,
expression
Split returns an empty array, that is, an array with no
elements and no data.
Optional. String character used to identify substring
limits. If omitted, the space character (" ") is assumed
delimiter to be the delimiter. If delimiter is a zero-length
string, a single-element array containing the entire
expression string is returned.
Optional. Number of substrings to be returned; -1
count
indicates that all substrings are returned.
Optional. Numeric value indicating the kind of
compare comparison to use when evaluating substrings. See
Settings section for values.
Settings
The compare argument can have the following values:
Remarks
The following example uses the Split function to return an array from a
string. The function performs a textual comparison of the delimiter, and
returns all of the substrings.
Syntax
Sqr(number)
The number argument can be any valid numeric expression greater than or
equal to 0.
Remarks
The following example uses the Sqr function to calculate the square root of a
number:
Dim MySqr
MySqr = Sqr(4) ' Returns 2.
MySqr = Sqr(23) ' Returns 4.79583152331272.
MySqr = Sqr(0) ' Returns 0.
MySqr = Sqr(-4) ' Generates a run-time error.
Description
Syntax
Part Description
string1 Required. Any valid string expression.
string2 Required. Any valid string expression.
Optional. Numeric value indicating the kind of
comparison to use when evaluating strings. If omitted,
compare
a binary comparison is performed. See Settings section
for values.
Settings
Return Values
The StrComp function has the following return values:
If StrComp returns
string1 is less than string2 -1
string1 is equal to string2 0
string1 is greater than string2 1
string1 or string2 is Null Null
Remarks
The following example uses the StrComp function to return the results of a
string comparison. If the third argument is 1, a textual comparison is
performed; if the third argument is 0 or omitted, a binary comparison is
performed.
Since these constants are built into VBScript, you don't have to define them
before using them. Use them anywhere in your code to represent the values
shown for each.
Description
Syntax
String(number, character)
The String function syntax has these arguments:
Part Description
Length of the returned string. If number contains
number
Null, Null is returned.
Character code specifying the character or string
expression whose first character is used to build the
character
return string. If character contains Null, Null is
returned.
Remarks
If you specify a number for character greater than 255, String converts the
number to a valid character code using the formula:
Syntax
StrReverse(string1)
The string1 argument is the string whose characters are to be reversed. If string1 is a zero-length
string (""), a zero-length string is returned. If string1 is Null, an error occurs.
Remarks
Dim MyStr
MyStr = StrReverse("VBScript") ' MyStr contains "tpircSBV".
Microsoft® Visual Basic® Scripting Edition Sub Language Reference
Version 1
Statement
See Also
Description
Declares the name, arguments, and code that form the body of a
Sub procedure.
Syntax
Part Description
ByVal Indicates that the argument is passed by value.
ByRef Indicates that the argument is passed by reference.
Name of the variable representing the argument; follows standard variable naming
varname
conventions.
Remarks
You can't define a Sub procedure inside any other procedure (e.g.
Function or Property Get).
Caution Sub procedures can be recursive, that is, they can call themselves to perform a given
task. However, recursion can lead to stack overflow.
Caution 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. If
your procedure refers to an undeclared variable that has the same name as another procedure,
constant or variable, it is assumed that your procedure is referring to that script-level name. To
avoid this kind of conflict, use an Option Explicit statement to force explicit declaration of
variables.
Microsoft® Visual Basic® Scripting Edition Tan Language Reference
Version 1
Function
See Also
Description
Syntax
Tan(number)
The number argument can be any valid numeric expression that expresses an angle in radians.
Remarks
Tan takes an angle and returns the ratio of two sides of a right triangle. The
ratio is the length of the side opposite the angle divided by the length of the
side adjacent to the angle.
To convert degrees to radians, multiply degrees by pi/180. To convert radians to degrees, multiply
radians by 180/pi.
The following example uses the Tan function to return the tangent of an angle:
Description
Syntax
Remarks
Class TestClass
Private Sub Class_Initialize ' Setup Initialize event.
MsgBox("TestClass started")
End Sub
Private Sub Class_Terminate ' Setup Terminate event.
MsgBox("TestClass terminated")
End Sub
End Class
Set X = New TestClass ' Create an instance of TestClass.
Set X = Nothing ' Destroy the instance.
Microsoft® Visual Basic® Scripting Edition Language Reference
Version 5
Test Method
See Also Applies to
Description
Syntax
object.Test(string)
Part Description
object Required. Always the name of a RegExp object.
string Required. The text string upon which the regular expression is executed.
Remarks
The actual pattern for the regular expression search is set using
the Pattern property of the RegExp object. The RegExp.Global
property has no effect on the Test method.
Description
Syntax
Time
Remarks
The following example uses the Time function to return the current system
time:
Dim MyTime
MyTime = Time ' Return current system time.
Microsoft® Visual Basic® Scripting Edition Timer Language Reference
Version 5
Function
See Also
Description
Syntax
Timer
Remarks
Function TimeIt(N)
Dim StartTime, EndTime
StartTime = Timer
For I = 1 To N
Next
EndTime = Timer
TimeIt = EndTime - StartTime
End Function
Microsoft® Visual Basic® Scripting Edition
Description
Returns a Variant of subtype Date containing the time for a specific hour,
minute, and second.
Syntax
Part Description
Number between 0 (12:00 A.M.) and 23 (11:00 P.M.),
hour
inclusive, or a numeric expression.
minute Any numeric expression.
second Any numeric expression.
Remarks
Dim MyTime1
MyTime1 = TimeSerial(12 - 6, -15, 0) ' Returns 5:45:00 AM
When any argument exceeds the accepted range for that argument, it
increments to the next larger unit as appropriate. For example, if you
specify 75 minutes, it is evaluated as one hour and 15 minutes. However, if
any single argument is outside the range -32,768 to 32,767, or if the time
specified by the three arguments, either directly or by expression, causes the
date to fall outside the acceptable range of dates, an error occurs.
Microsoft® Visual Basic® Scripting Edition
Description
Syntax
TimeValue(time)
The time argument is usually a string expression representing a time from 0:00:00 (12:00:00 A.M.) to
23:59:59 (11:59:59 P.M.), inclusive. However, time can also be any expression that represents a time
in that range. If time contains Null, Null is returned.
Remarks
You can enter valid times using a 12-hour or 24-hour clock. For example,
"2:24PM" and "14:24" are both valid time arguments. If the time argument
contains date information, TimeValue doesn't return the date information.
However, if time includes invalid date information, an error occurs.
The following example uses the TimeValue function to convert a string to a time. You can also use
date literals to directly assign a time to a Variant (for example, MyTime = #4:35:17 PM#).
Dim MyTime
MyTime = TimeValue("4:35:17 PM") ' MyTime contains
Language Reference
Microsoft® Visual Basic® Scripting Edition True Version 1
See Also
Description
Description
Syntax
TypeName(varname)
The required varname argument can be any variable.
Return Values
Value Description
Byte Byte value
Integer Integer value
Long Long integer value
Single Single-precision floating-point value
Double Double-precision floating-point value
Currency Currency value
Decimal Decimal value
Date Date or time value
String Character string value
Boolean Boolean value; True or False
Empty Unitialized
Null No valid data
<object; Actual type name of an object
type>
Object Generic object
Unknown Unknown object type
Object variable that doesn't yet refer to an object
Nothing
instance
Error Error
Remarks
Description
Syntax
UBound(arrayname[, dimension])
The UBound function syntax has these parts:
Part Description
Required. Name of the array variable; follows
arrayname
standard variable naming conventions.
Optional. Whole number indicating which
dimension's upper bound is returned. Use 1 for the
dimension
first dimension, 2 for the second, and so on. If
dimension is omitted, 1 is assumed.
Remarks
The UBound function is used with the LBound function to determine the
size of an array. Use the LBound function to find the lower limit of an
array dimension.
The lower bound for any dimension is always 0. As a result, UBound returns the following values
for an array with these dimensions:
Dim A(100,3,4)
Statement Return Value
UBound(A, 1) 100
UBound(A, 2) 3
UBound(A, 3) 4
Microsoft® Visual Basic® Scripting Edition UCase Language Reference
Version 1
Function
See Also
Description
Syntax
UCase(string)
The string argument is any valid string expression. If string contains Null, Null is returned.
Remarks
Only lowercase letters are converted to uppercase; all uppercase letters and
nonletter characters remain unchanged.
The following example uses the UCase function to return an uppercase version of a string:
Dim MyWord
MyWord = UCase("Hello World") ' Returns "HELLO WO
Microsoft® Visual Basic® Scripting Edition Value Language Reference
Version 5
Property
See Also Applies To
Description
Syntax
object.Value
Remarks
These constants are only available when your project has an explicit reference to
the appropriate type library containing these constant definitions. For VBScript,
you must explicitly declare these constants in your code.
See Also
Description
Syntax
VarType(varname)
The varname argument can be any variable.
Return Values
Remarks
The VarType function never returns the value for Array by itself. It is
always added to some other value to indicate an array of a particular type.
The value for Variant is only returned when it has been added to the value
for Array to indicate that the argument to the VarType function is an array.
For example, the value returned for an array of integers is calculated as 2 +
8192, or 8194. If an object has a default property, VarType (object) returns
the type of its default property.
The following example uses the VarType function to determine the subtype of a variable.
Dim MyCheck
MyCheck = VarType(300) ' Returns 2.
MyCheck = VarType(#10/19/62#) ' Returns 7.
MyCheck = VarType("VBScript") ' Returns 8.
Microsoft® Visual Basic® Scripting Edition
A number of useful constants you can use in your code are built into VBScript.
Constants provide a convenient way to use specific values without actually
having to remember the value itself. Using constants also makes your code more
maintainable should the value of any constant ever change. Because these
constants are already defined in VBScript, you don't need to explicitly declare
them in your code. Simply use them in place of the values they represent.
Here are the various categories of constants provided in VBScript and a brief description of each:
Color Constants
Defines eight basic colors that can be used in scripting.
Miscellaneous Constants
Defines constants that don't conveniently fit into any other category.
MsgBox Constants
Defines constants used in the MsgBox function to describe button visibility, labeling, behavior, and return
values.
String Constants
Defines a variety of non-printable characters used in string manipulation.
Tristate Constants
Defines constants used with functions that format numbers.
VarType Constants
Defines the various Variant subtypes.
Microsoft® Visual Basic® Scripting Edition
Language Reference
Weekday Function Version 1
See Also
Description
Syntax
Weekday(date, [firstdayofweek])
The Weekday function syntax has these arguments:
Part Description
Any expression that can represent a date. If date
date
contains Null, Null is returned.
A constant that specifies the first day of the
firstdayofweek
week. If omitted, vbSunday is assumed.
Settings
Remarks
The following example uses the Weekday function to obtain the day of the
week from a specified date:
Description
Syntax
While condition
Version [statements]
Wend
The While...Wend statement syntax has these parts:
Part Description
Numeric or string expression that evaluates to True
condition or False. If condition is Null, condition is treated as
False.
One or more statements executed while condition is
statements
True.
Remarks
Dim Counter
Counter = 0 ' Initialize variable.
While Counter < 20 ' Test value of Counter.
Counter = Counter + 1 ' Increment Counter.
Alert Counter
Wend ' End While loop when Counter > 19.
Microsoft® Visual Basic® Scripting Edition With Language Reference
Version 5
Statement
See Also
Description
Syntax
With object
statements
End With
Part Description
object Required. Name of an object or a function that returns an object.
statements Required. One or more statements to be executed on object.
Remarks
Note Once a With block is entered, object can't be changed. As a result, you can't use a single
With statement to affect a number of different objects.
You can nest With statements by placing one With block within
another. However, because members of outer With blocks are
masked within the inner With blocks, you must provide a fully
qualified object reference in an inner With block to any member
of an object in an outer With block.
Important Do not jump into or out of With blocks. If statements in a With block are executed,
but either the With or End With statement is not executed, you may get errors or unpredictable
behavior.
Microsoft® Visual Basic® Scripting Edition Xor Language Reference
Version 1
Operator
See Also
Description
Syntax
Part Description
result Any numeric variable.
expression1 Any expression.
expression2 Any expression.
Remarks
If one, and only one, of the expressions evaluates to True, result is True.
However, if either expression is Null, result is also Null. When neither
expression is Null, result is determined according to the following table:
If bit in expression1
And bit in expression2 is Then result is
is
0 0 0
0 1 1
1 0 1
1 1 0
Microsoft® Visual Basic® Scripting Edition Year Language Reference
Version 1
Function
See Also
Description
Syntax
Year(date)
The date argument is any expression that can represent a date. If date contains Null, Null is returned.
Remarks
The following example uses the Year function to obtain the year from a
specified date:
Since these constants are built into VBScript, you don't have to define them
before using them. Use them anywhere in your code to represent the values
shown for each.
Since these constants are built into VBScript, you don't have to define them
before using them. Use them anywhere in your code to represent the values
shown for each.
Description
Syntax
Part Description
result Any numeric variable.
expression Any expression.
comparisonoperator Any comparison operator.
object Any object name.
Remarks
The Is operator has specific comparison functionality that differs from the
operators in the following table. The following table contains a list of the
comparison operators and the conditions that determine whether result is
True, False, or Null:
The following table shows how expressions are compared or what results from the comparison,
depending on the underlying subtype:
If Then
Both expressions are
Perform a numeric comparison.
numeric
Both expressions are
Perform a string comparison.
strings
One expression is
The numeric expression is less than the
numeric and the other
string expression.
is a string
One expression is
Perform a numeric comparison, using 0
Empty and the other is
as the Empty expression.
numeric
One expression is Perform a string comparison, using a
Empty and the other is zero-length string ("") as the Empty
a string expression.
Both expressions are
The expressions are equal.
Empty
Microsoft® Visual Basic® Scripting Edition
Reference
(Dictionary)
See Also Applies to
Description
Syntax
Part Description
object Required. Always the name of a Dictionary object.
key Required. The key associated with the item being added.
item Required. The item associated with the key being added.
Remarks
Description
Syntax
object.Add(folderName)
The Add method has the following parts:
Part Description
object Required. Always the name of a Folders collection.
Required. The name of the new Folder being
folderName
added.
Remarks
The following example illustrates the use of the Add method to add a new
folder:
Description
Syntax
object.AtEndOfLine
The object is always the name of a TextStream object.
Remarks
The AtEndOfLine property applies only to TextStream files that are open
for reading; otherwise, an error occurs.
The following code illustrates the use of the AtEndOfLine property:
Function ReadEntireFile(filespec)
Const ForReading = 1
Dim fso, theFile, retstring
Set fso = CreateObject("Scripting.FileSystemObject")
Set theFile = fso.OpenTextFile(filespec, ForReading, False
Do While theFile.AtEndOfLine <> True
retstring = theFile.Read(1)
Loop
theFile.Close
ReadEntireFile = retstring
End Function
Microsoft® Visual Basic® Scripting Edition
Description
Returns True if the file pointer is at the end of a TextStream file; False if it
is not. Read-only.
Syntax
object.AtEndOfStream
The object is always the name of a TextStream object.
Remarks
Function ReadEntireFile(filespec)
Const ForReading = 1
Dim fso, theFile, retstring
Set fso = CreateObject("Scripting.FileSystemObject")
Set theFile = fso.OpenTextFile(filespec, ForReading, False
Do While theFile.AtEndOfStream <> True
retstring = theFile.ReadLine
Loop
theFile.Close
ReadEntireFile = retstring
End Function
Microsoft® Visual Basic® Scripting Edition
Description
Syntax
object.Attributes [= newattributes]
The Attributes property has these parts:
Part Description
Required. Always the name of a File or Folder
object
object.
Optional. If provided, newattributes is the new
newattributes
value for the attributes of the specified object.
Settings
The newattributes argument can have any of the following values or any
logical combination of the following values:
Remarks
The following code illustrates the use of the Attributes property with a file:
Function ToggleArchiveBit(filespec)
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(filespec)
If f.attributes and 32 Then
f.attributes = f.attributes - 32
ToggleArchiveBit = "Archive bit is cleared."
Else
f.attributes = f.attributes + 32
ToggleArchiveBit = "Archive bit is set."
End If
End Function
Microsoft® Visual Basic® Scripting Edition
Description
Syntax
object.AvailableSpace
The object is always a Drive object.
Remarks
Function ShowAvailableSpace(drvPath)
Dim fso, d, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set d = fso.GetDrive(fso.GetDriveName(drvPath))
s = "Drive " & UCase(drvPath) & " - "
s = s & d.VolumeName & "<BR>"
s = s & "Available Space: " & FormatNumber(d.AvailableSpace/1024, 0)
s = s & " Kbytes"
ShowAvailableSpace = s
End Function
Microsoft® Visual Basic® Scripting Edition
Scripting Run-Time Reference
BuildPath Method Version 3
Description
Syntax
object.BuildPath(path, name)
The BuildPath method syntax has these parts:
Part Description
object Required. Always the name of a FileSystemObject.
Required. Existing path to which name is appended. Path
path can be absolute or relative and need not specify an
existing folder.
name Required. Name being appended to the existing path.
Remarks
Function GetBuildPath(path)
Dim fso, newpath
Set fso = CreateObject("Scripting.FileSystemObject")
newpath = fso.BuildPath(path, "Sub Folder")
GetBuildPath = newpath
End Function
Microsoft® Visual Basic® Scripting Edition Close Scripting Run-Time Reference
Version 2
Method
See Also Applies to
Description
Syntax
object.Close
The object is always the name of a TextStream object.
Remarks
The following example illustrates use of the Close method to close an open
TextStream file:
Sub CreateAFile
Dim fso, MyFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.CreateTextFile("c:\testfile.txt", True)
MyFile.WriteLine("This is a test.")
MyFile.Close
End Sub
Microsoft® Visual Basic® Scripting Edition Column Scripting Run-Time Reference
Version 2
Property
See Also Applies to
Description
Read-only property that returns the column number of the current character
position in a TextStream file.
Syntax
object.Column
The object is always the name of a TextStream object.
Remarks
After a newline character has been written, but before any other character is
written, Column is equal to 1.
The following example illustrates use of the Column property:
Function GetColumn
Const ForReading = 1, ForWriting = 2
Dim fso, f, m
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True
f.Write "Hello world!"
f.Close
Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
m = f.ReadLine
GetColumn = f.Column
End Function
Microsoft® Visual Basic® Scripting Edition
Description
Sets and returns the comparison mode for comparing string keys in a
Dictionary object.
Syntax
object.CompareMode[ = compare]
The CompareMode property has the following parts:
Part Description
object Required. Always the name of a Dictionary object.
Optional. If provided, compare is a value representing
compare the comparison mode used by functions such as
StrComp.
Settings
Remarks
Dim d
Set d = CreateObject("Scripting.Dictionary")
d.CompareMode = vbTextCompare
d.Add "a", "Athens" ' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
d.Add "B", "Baltimore" ' Add method fails on this line bec
' letter b already exists in the Dictionary.
Microsoft® Visual Basic® Scripting Edition Copy Scripting Run-Time Reference
Version 3
Method
See Also Applies To
Description
Syntax
Part Description
Required. Always the name of a File or Folder
object
object.
Required. Destination where the file or folder is to
destination
be copied. Wildcard characters are not allowed.
Optional. Boolean value that is True (default) if
overwrite existing files or folders are to be overwritten; False
if they are not.
Remarks
Description
Syntax
Part Description
Required. The object is always the name of a
object
FileSystemObject.
Required. Character string file specification, which
source can include wildcard characters, for one or more
files to be copied.
Required. Character string destination where the file
destination or files from source are to be copied. Wildcard
characters are not allowed.
Optional. Boolean value that indicates if existing
files are to be overwritten. If True, files are
overwritten; if False, they are not. The default is
overwrite
True. Note that CopyFile will fail if destination has
the read-only attribute set, regardless of the value of
overwrite.
Remarks
Wildcard characters can only be used in the last path component of the
source argument. For example, you can use:
FileSystemObject.CopyFile "c:\mydocuments\letters\*.doc", "c:\tempfolder\"
But you can't use:
If destination does not exist, source gets copied. This is the usual case.
If destination is an existing file, an error occurs if overwrite is False.
Otherwise, an attempt is made to copy source over the existing file.
If destination is a directory, an error occurs.
An error also occurs if a source using wildcard characters doesn't match any
files. The CopyFile method stops on the first error it encounters. No
attempt is made to roll back or undo any changes made before an error
occurs.
Microsoft® Visual Basic® Scripting Edition
Description
Syntax
Part Description
object Required. Always the name of a FileSystemObject.
Required. Character string folder specification,
source which can include wildcard characters, for one or
more folders to be copied.
Required. Character string destination where the
destination folder and subfolders from source are to be copied.
Wildcard characters are not allowed.
Optional. Boolean value that indicates if existing
folders are to be overwritten. If True, files are
overwrite
overwritten; if False, they are not. The default is
True.
Remarks
Wildcard characters can only be used in the last path component of the
source argument. For example, you can use:
If destination does not exist, the source folder and all its contents gets
copied. This is the usual case.
If destination is an existing file, an error occurs.
If destination is a directory, an attempt is made to copy the folder and
all its contents. If a file contained in source already exists in
destination, an error occurs if overwrite is False. Otherwise, it will
attempt to copy the file over the existing file.
If destination is a read-only directory, an error occurs if an attempt is
made to copy an existing read-only file into that directory and
overwrite is False.
An error also occurs if a source using wildcard characters doesn't match any
folders.
The CopyFolder method stops on the first error it encounters. No attempt is made to roll back any
changes made before an error occurs.
Microsoft® Visual Basic® Scripting Edition Count Scripting Run-Time Reference
Version 2
Property
See Also Applies To
Description
Syntax
object.Count
The object is always the name of one of the items in the Applies To list.
Remarks
Function ShowKeys
Dim a, d, i, s ' Create some variables.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens" ' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
a = d.Keys ' Get the keys.
For i = 0 To d.Count -1 ' Iterate the array.
s = s & a(i) & "<BR>" ' Create return string.
Next
ShowKeys = s
End Function
Microsoft® Visual Basic® Scripting Edition
Description
Creates a folder.
Syntax
object.CreateFolder(foldername)
The CreateFolder method has these parts:
Part Description
object Required. Always the name of a FileSystemObject.
Required. String expression that identifies the folder
foldername
to create.
Remarks
Function CreateFolderDemo
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.CreateFolder("c:\New Folder")
CreateFolderDemo = f.Path
End Function
Microsoft® Visual Basic® Scripting Edition
Description
Creates a specified file name and returns a TextStream object that can be
used to read from or write to the file.
Syntax
Part Description
Required. Always the name of a FileSystemObject or
object
Folder object.
Required. String expression that identifies the file to
filename
create.
Optional. Boolean value that indicates if an existing
file can be overwritten. The value is True if the file
overwrite
can be overwritten; False if it can't be overwritten. If
omitted, existing files are not overwritten.
Optional. Boolean value that indicates whether the file
is created as a Unicode or ASCII file. The value is
unicode True if the file is created as a Unicode file; False if
it's created as an ASCII file. If omitted, an ASCII file
is assumed.
Remarks
Sub CreateAfile
Dim fso, MyFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.CreateTextFile("c:\testfile.txt", True)
MyFile.WriteLine("This is a test.")
MyFile.Close
End Sub
If the overwrite argument is False, or is not provided, for a filename that
already exists, an error occurs.
Microsoft® Visual Basic® Scripting Edition
Description
Returns the date and time that the specified file or folder was created. Read-
only.
Syntax
object.DateCreated
The object is always a File or Folder object.
Remarks
The following code illustrates the use of the DateCreated property with a
file:
Function ShowFileInfo(filespec)
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(filespec)
ShowFileInfo = "Created: " & f.DateCreated
End Function
Microsoft® Visual Basic® Scripting Edition
Description
Returns the date and time that the specified file or folder was last accessed.
Read-only.
Syntax
object.DateLastAccessed
The object is always a File or Folder object.
Remarks
Function ShowFileAccessInfo(filespec)
Dim fso, f, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(filespec)
s = UCase(filespec) & "<BR>"
s = s & "Created: " & f.DateCreated & "<BR>"
s = s & "Last Accessed: " & f.DateLastAccessed & "<BR>"
s = s & "Last Modified: " & f.DateLastModified
ShowFileAccessInfo = s
End Function
Important This method depends on the underlying operating system for its behavior.
If the operating system does not support providing time information, none will be
returned.
Microsoft® Visual Basic® Scripting Edition
Description
Returns the date and time that the specified file or folder was last modified.
Read-only.
Syntax
object.DateLastModified
The object is always a File or Folder object.
Remarks
Function ShowFileAccessInfo(filespec)
Dim fso, f, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(filespec)
s = UCase(filespec) & "<BR>"
s = s & "Created: " & f.DateCreated & "<BR>"
s = s & "Last Accessed: " & f.DateLastAccessed & "<BR>"
s = s & "Last Modified: " & f.DateLastModified
ShowFileAccessInfo = s
End Function
Microsoft® Visual Basic® Scripting Edition Delete Scripting Run-Time Reference
Version 3
Method
See Also Applies To
Description
Syntax
object.Delete force
The Delete method syntax has these parts:
Part Description
object Required. Always the name of a File or Folder object.
Optional. Boolean value that is True if files or folders
force with the read-only attribute set are to be deleted; False
(default) if they are not.
Remarks
An error occurs if the specified file or folder does not exist. The Delete
method does not distinguish between folders that have contents and those
that do not. The specified folder is deleted regardless of whether or not it
has contents.
The results of the Delete method on a File or Folder are identical to operations performed using
FileSystemObject.DeleteFile or FileSystemObject.DeleteFolder.
Description
Syntax
Part Description
object Required. Always the name of a FileSystemObject.
Required. The name of the file to delete. The filespec
filespec can contain wildcard characters in the last path
component.
Optional. Boolean value that is True if files with the
force read-only attribute set are to be deleted; False (default)
if they are not.
Remarks
Sub DeleteAFile(filespec)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
fso.DeleteFile(filespec)
End Sub
Microsoft® Visual Basic® Scripting Edition
Description
Syntax
Part Description
object Required. Always the name of a FileSystemObject.
Required. The name of the folder to delete. The
folderspec folderspec can contain wildcard characters in the last
path component.
Optional. Boolean value that is True if folders with
force the read-only attribute set are to be deleted; False
(default) if they are not.
Remarks
The DeleteFolder method does not distinguish between folders that have
contents and those that do not. The specified folder is deleted regardless of
whether or not it has contents.
An error occurs if no matching folders are found. The DeleteFolder method stops on the first error it
encounters. No attempt is made to roll back or undo any changes that were made before an error
occurred.
Description
Remarks
Description
Remarks
The following code illustrates the use of the Drive object to access drive
properties:
Function ShowFreeSpace(drvPath)
Dim fso, d, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set d = fso.GetDrive(fso.GetDriveName(drvPath))
s = "Drive " & UCase(drvPath) & " - "
s = s & d.VolumeName & "<BR>"
s = s & "Free Space: " & FormatNumber(d.FreeSpace/1024, 0)
s = s & " Kbytes"
ShowFreeSpace = s
End Function
Microsoft® Visual Basic® Scripting Edition Drive Scripting Run-Time Reference
Version 3
Property
See Also Applies To
Description
Returns the drive letter of the drive on which the specified file or folder
resides. Read-only.
Syntax
object.Drive
The object is always a File or Folder object.
Remarks
Function ShowFileAccessInfo(filespec)
Dim fso, f, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(filespec)
s = f.Name & " on Drive " & UCase(f.Drive) & "<BR>"
s = s & "Created: " & f.DateCreated & "<BR>"
s = s & "Last Accessed: " & f.DateLastAccessed & "<BR>"
s = s & "Last Modified: " & f.DateLastModified
ShowFileAccessInfo = s
End Function
Microsoft® Visual Basic® Scripting Edition
Description
Syntax
object.DriveExists(drivespec)
The DriveExists method syntax has these parts:
Part Description
object Required. Always the name of a FileSystemObject.
Required. A drive letter or a complete path
drivespec
specification.
Remarks
For drives with removable media, the DriveExists method returns True
even if there are no media present. Use the IsReady property of the Drive
object to determine if a drive is ready.
The following example illustrates use of the DriveExists method:
Function ReportDriveStatus(drv)
Dim fso, msg
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.DriveExists(drv) Then
msg = ("Drive " & UCase(drv) & " exists.")
Else
msg = ("Drive " & UCase(drv) & " doesn't exist.")
End If
ReportDriveStatus = msg
End Function
Microsoft® Visual Basic® Scripting Edition
Description
Returns the drive letter of a physical local drive or a network share. Read-
only.
Syntax
object.DriveLetter
The object is always a Drive object.
Remarks
Function ShowDriveLetter(drvPath)
Dim fso, d, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set d = fso.GetDrive(fso.GetDriveName(drvPath))
s = "Drive " & d.DriveLetter & ": - "
s = s & d.VolumeName & "<BR>"
s = s & "Free Space: " & FormatNumber(d.FreeSpace/1024, 0)
s = s & " Kbytes"
ShowDriveLetter = s
End Function
Microsoft® Visual Basic® Scripting Edition Scripting Run-Time Reference
Version 3
Drives Collection
See Also Properties Methods
Description
Remarks
Removable-media drives need not have media inserted for them to appear
in the Drives collection.
The following code illustrates how to get the Drives collection and iterate the collection using the
For Each...Next statement:
Function ShowDriveList
Dim fso, d, dc, s, n
Set fso = CreateObject("Scripting.FileSystemObject")
Set dc = fso.Drives
For Each d in dc
n = ""
s = s & d.DriveLetter & " - "
If d.DriveType = Remote Then
n = d.ShareName
ElseIf d.IsReady Then
n = d.VolumeName
End If
s = s & n & "<BR>"
Next
ShowDriveList = s
End Function
Microsoft® Visual Basic® Scripting Edition Drives Scripting Run-Time Reference
Version 3
Property
See Also Applies To
Description
Syntax
object.Drives
The object is always a FileSystemObject.
Remarks
Removable-media drives need not have media inserted for them to appear
in the Drives collection.
You can iterate the members of the Drives collection using a For Each...Next construct as illustrated
in the following code:
Function ShowDriveList
Dim fso, d, dc, s, n
Set fso = CreateObject("Scripting.FileSystemObject")
Set dc = fso.Drives
For Each d in dc
n = ""
s = s & d.DriveLetter & " - "
If d.DriveType = 3 Then
n = d.ShareName
ElseIf d.IsReady Then
n = d.VolumeName
End If
s = s & n & "<BR>"
Next
ShowDriveList = s
End Function
Microsoft® Visual Basic® Scripting Edition
These constants are only available when your project has an explicit reference to
the appropriate type library containing these constant definitions. For VBScript,
you must explicitly declare these constants in your code.
Description
Syntax
object.DriveType
The object is always a Drive object.
Remarks
Function ShowDriveType(drvpath)
Dim fso, d, t
Set fso = CreateObject("Scripting.FileSystemObject")
Set d = fso.GetDrive(drvpath)
Select Case d.DriveType
Case 0: t = "Unknown"
Case 1: t = "Removable"
Case 2: t = "Fixed"
Case 3: t = "Network"
Case 4: t = "CD-ROM"
Case 5: t = "RAM Disk"
End Select
ShowDriveType = "Drive " & d.DriveLetter & ": - " & t
End Function
Microsoft® Visual Basic® Scripting Edition Exists Scripting Run-Time Reference
Version 2
Method
See Also Applies to
Description
Syntax
object.Exists(key)
The Exists method syntax has these parts:
Part Description
object Required. Always the name of a Dictionary object.
Required. Key value being searched for in the Dictionary
key
object.
Remarks
Function KeyExistsDemo
Dim d, msg ' Create some variables.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens" ' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
If d.Exists("c") Then
msg = "Specified key exists."
Else
msg = "Specified key doesn't exist."
End If
KeyExistsDemo = msg
End Function
Microsoft® Visual Basic® Scripting Edition File
Scripting Run-Time Reference
Attribute Version 3
Constants
See Also
These constants are only available when your project has an explicit reference to
the appropriate type library containing these constant definitions. For VBScript,
you must explicitly declare these constants in your code.
Constants
See Also
These constants are only available when your project has an explicit reference to
the appropriate type library containing these constant definitions. For VBScript,
you must explicitly declare these constants in your code.
Description
Syntax
object.FileExists(filespec)
The FileExists method syntax has these parts:
Part Description
object Required. Always the name of a FileSystemObject.
Required. The name of the file whose existence is to be
determined. A complete path specification (either
filespec
absolute or relative) must be provided if the file isn't
expected to exist in the current folder.
Remarks
Function ReportFileStatus(filespec)
Dim fso, msg
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(filespec)) Then
msg = filespec & " exists."
Else
msg = filespec & " doesn't exist."
End If
ReportFileStatus = msg
End Function
Microsoft® Visual Basic® Scripting Edition File Scripting Run-Time Reference
Version 3
Object
See Also Properties Methods
Description
Remarks
The following code illustrates how to obtain a File object and how to view
one of its properties.
Function ShowDateCreated(filespec)
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(filespec)
ShowDateCreated = f.DateCreated
End Function
Microsoft® Visual Basic® Scripting Edition Files Scripting Run-Time Reference
Version 3
Collection
See Also Properties Methods
Description
Remarks
The following code illustrates how to get a Files collection and iterate the
collection using the For Each...Next statement:
Function ShowFolderList(folderspec)
Dim fso, f, f1, fc, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(folderspec)
Set fc = f.Files
For Each f1 in fc
s = s & f1.name
s = s & "<BR>"
Next
ShowFolderList = s
End Function
Microsoft® Visual Basic® Scripting Edition Files Scripting Run-Time Reference
Version 3
Property
See Also Applies To
Description
Syntax
object.Files
The object is always a Folder object.
Remarks
Function ShowFileList(folderspec)
Dim fso, f, f1, fc, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(folderspec)
Set fc = f.Files
For Each f1 in fc
s = s & f1.name
s = s & "<BR>"
Next
ShowFileList = s
End Function
Microsoft® Visual Basic® Scripting Edition
Description
Remarks
FileSystemObject has a number of useful constants that you can use in your
code. Constants provide a convenient way to use specific values without actually
having to remember the value itself. They also makes your code more
maintainable, should the value of any constant ever change.
Depending on your scripting host, these constants may be already defined. If so, simply use the constants
anywhere in your code in place of the values they represent. In cases where SCRRUN.DLL is not explicitly
referenced by your scripting host, you'll have to define these constants in your code before you can use
them. Examples of this case include Microsoft Internet Explorer and Microsoft Internet Information
Services (IIS).
The following list describes the various categories of constants provided for the FileSystemObject, along
with a brief description:
DriveType Constants
Defines the various drive types available on the host computer, such as Fixed, Removable, CD-ROM, etc.
SpecialFolder Constants
Defines special folders available in your operating system.
Microsoft® Visual Basic® Scripting Edition
Description
Returns the type of file system in use for the specified drive.
Syntax
object.FileSystem
The object is always a Drive object.
Remarks
Function ShowFileSystemType(drvspec)
Dim fso,d
Set fso = CreateObject("Scripting.FileSystemObject")
Set d = fso.GetDrive(drvspec)
ShowFileSystemType = d.FileSystem
End Function
Microsoft® Visual Basic® Scripting Edition Folder Scripting Run-Time Reference
Version 3
Object
See Also Properties Methods
Description
Remarks
The following code illustrates how to obtain a Folder object and how to
return one of its properties:
Function ShowDateCreated(folderspec)
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(folderspec)
ShowDateCreated = f.DateCreated
End Function
Microsoft® Visual Basic® Scripting Edition Folders Scripting Run-Time Reference
Version 3
Collection
See Also Properties Methods
Description
Remarks
The following code illustrates how to get a Folders collection and how to
iterate the collection using the For Each...Next statement:
Function ShowFolderList(folderspec)
Dim fso, f, f1, fc, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(folderspec)
Set fc = f.SubFolders
For Each f1 in fc
s = s & f1.name
s = s & "<BR>"
Next
ShowFolderList = s
End Function
Microsoft® Visual Basic® Scripting Edition
Description
Syntax
object.FolderExists(folderspec)
The FolderExists method syntax has these parts:
Part Description
object Required. Always the name of a FileSystemObject.
Required. The name of the folder whose existence is
to be determined. A complete path specification
folderspec
(either absolute or relative) must be provided if the
folder isn't expected to exist in the current folder.
Remarks
Function ReportFolderStatus(fldr)
Dim fso, msg
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FolderExists(fldr)) Then
msg = fldr & " exists."
Else
msg = fldr & " doesn't exist."
End If
ReportFolderStatus = msg
End Function
Microsoft® Visual Basic® Scripting Edition
Description
Returns the amount of free space available to a user on the specified drive
or network share. Read-only.
Syntax
object.FreeSpace
The object is always a Drive object.
Remarks
The value returned by the FreeSpace property is typically the same as that
returned by the AvailableSpace property. Differences may occur between
the two for computer systems that support quotas.
The following code illustrates the use of the FreeSpace property:
Function ShowFreeSpace(drvPath)
Dim fso, d, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set d = fso.GetDrive(fso.GetDriveName(drvPath))
s = "Drive " & UCase(drvPath) & " - "
s = s & d.VolumeName & "<BR>"
s = s & "Free Space: " & FormatNumber(d.FreeSpace/1024, 0)
s = s & " Kbytes"
ShowFreeSpace = s
End Function
Microsoft® Visual Basic® Scripting Edition
Scripting Run-
GetAbsolutePathName Time Reference
Version 3
Method
See Also Applies To
Description
Syntax
object.GetAbsolutePathName(pathspec)
The GetAbsolutePathName method syntax has these parts:
Part Description
object Required. Always the name of a FileSystemObject.
Required. Path specification to change to a complete
pathspec
and unambiguous path.
Remarks
Description
Returns a string containing the base name of the file (less any file
extension), or folder in a provided path specification.
Syntax
object.GetBaseName(path)
The GetBaseName method syntax has these parts:
Part Description
object Required. Always the name of a FileSystemObject.
Required. The path specification for the file or folder
path
whose base name is to be returned.
Remarks
Function GetTheBase(filespec)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
GetTheBase = fso.GetBaseName(filespec)
End Function
Note The GetBaseName method works only on the provided
path string. It does not attempt to resolve the path, nor does it
check for the existence of the specified path.
Microsoft® Visual Basic® Scripting Edition
Scripting Run-Time Reference
GetDrive Method Version 3
Description
Syntax
object.GetDrive drivespec
The GetDrive method syntax has these parts:
Part Description
object Required. Always the name of a FileSystemObject.
Required. The drivespec argument can be a drive
letter (c), a drive letter with a colon appended (c:), a
drivespec drive letter with a colon and path separator appended
(c:\), or any network share specification
(\\computer2\share1).
Remarks
For network shares, a check is made to ensure that the share exists.
An error occurs if drivespec does not conform to one of the accepted forms or does not exist. To call
the GetDrive method on a normal path string, use the following sequence to get a string that is
suitable for use as drivespec:
DriveSpec = GetDriveName(GetAbsolutePathName(Path))
The following example illustrates use of the GetDrive method:
Function ShowFreeSpace(drvPath)
Dim fso, d, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set d = fso.GetDrive(fso.GetDriveName(drvPath))
s = "Drive " & UCase(drvPath) & " - "
s = s & d.VolumeName & "<BR>"
s = s & "Free Space: " & FormatNumber(d.FreeSpace/1024, 0)
s = s & " Kbytes"
ShowFreeSpace = s
End Function
Microsoft® Visual Basic® Scripting Edition
Description
Returns a string containing the name of the drive for a specified path.
Syntax
object.GetDriveName(path)
The GetDriveName method syntax has these parts:
Part Description
object Required. Always the name of a FileSystemObject.
Required. The path specification for the component
path
whose drive name is to be returned.
Remarks
Function GetAName(DriveSpec)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
GetAName = fso.GetDriveName(Drivespec)
End Function
Note The GetDriveName method works only on the provided
path string. It does not attempt to resolve the path, nor does it
check for the existence of the specified path.
Microsoft® Visual Basic® Scripting Edition
Description
Returns a string containing the extension name for the last component in a
path.
Syntax
object.GetExtensionName(path)
The GetExtensionName method syntax has these parts:
Part Description
object Required. Always the name of a FileSystemObject.
Required. The path specification for the component
path
whose extension name is to be returned.
Remarks
Function GetAnExtension(DriveSpec)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
GetAnExtension = fso.GetExtensionName(Drivespec
End Function
Microsoft® Visual Basic® Scripting Edition GetFile Scripting Run-Time Reference
Version 3
Method
See Also Applies To
Description
Syntax
object.GetFile(filespec)
The GetFile method syntax has these parts:
Part Description
object Required. Always the name of a FileSystemObject.
Required. The filespec is the path (absolute or relative)
filespec
to a specific file.
Remarks
Function ShowFileAccessInfo(filespec)
Dim fso, f, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(filespec)
s = f.Path & "<br>"
s = s & "Created: " & f.DateCreated & "<br>"
s = s & "Last Accessed: " & f.DateLastAccessed & "<br>"
s = s & "Last Modified: " & f.DateLastModified
ShowFileAccessInfo = s
End Function
Microsoft® Visual Basic® Scripting Edition
Description
Returns the last file name or folder of a specified path that is not part of the
drive specification.
Syntax
object.GetFileName(pathspec)
The GetFileName method syntax has these parts:
Part Description
object Required. Always the name of a FileSystemObject.
Required. The path (absolute or relative) to a specific
pathspec
file.
Remarks
Function GetAName(DriveSpec)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
GetAName = fso.GetFileName(DriveSpec)
End Function
Note The GetFileName method works only on the provided
path string. It does not attempt to resolve the path, nor does it
check for the existence of the specified path.
Microsoft® Visual Basic® Scripting Edition
Description
Syntax
object.GetFileVersion(pathspec)
The GetVersion method syntax has these parts:
Part Description
object Required. Always the name of a FileSystemObject.
Required. The path (absolute or relative) to a specific
pathspec
file.
Remarks
Function GetVersion(PathSpec)
Dim fso, temp
Set fso = CreateObject("Scripting.FileSystemObject")
temp = fso.GetFileVersion(PathSpec)
If Len(temp) Then
GetVersion = temp
Else
GetVersion = "No version information available."
End If
End Function
Description
Syntax
object.GetFolder(folderspec)
The GetFolder method syntax has these parts:
Part Description
object Required. Always the name of a FileSystemObject.
Required. The folderspec is the path (absolute or
folderspec
relative) to a specific folder.
Remarks
Scripting Run-
GetParentFolderName Time Reference
Version 3
Method
See Also Applies To
Description
Returns a string containing the name of the parent folder of the last file or
folder in a specified path.
Syntax
object.GetParentFolderName(path)
The GetParentFolderName method syntax has these parts:
Part Description
object Required. Always the name of a FileSystemObject.
Required. The path specification for the file or folder
path
whose parent folder name is to be returned.
Remarks
Function GetTheParent(DriveSpec)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
GetTheParent = fso.GetParentFolderName(Drivespec
End Function
Note The GetParentFolderName method works only on the
provided path string. It does not attempt to resolve the path, nor
does it check for the existence of the specified path.
Microsoft® Visual Basic® Scripting Edition
Description
Syntax
object.GetSpecialFolder(folderspec)
The GetSpecialFolder method syntax has these parts:
Part Description
object Required. Always the name of a FileSystemObject.
Required. The name of the special folder to be
folderspec returned. Can be any of the constants shown in the
Settings section.
Settings
Function CreateTempFile
Dim tfolder, tname, tfile
Const TemporaryFolder = 2
Set tfolder = fso.GetSpecialFolder(TemporaryFolder)
tname = fso.GetTempName
Set tfile = tfolder.CreateTextFile(tname)
Set CreateTempFile = tfile
End Function
Description
Syntax
object.GetTempName
The optional object is always the name of a FileSystemObject.
Remarks
Function CreateTempFile
Dim tfolder, tname, tfile
Const TemporaryFolder = 2
Set tfolder = fso.GetSpecialFolder(TemporaryFolder)
tname = fso.GetTempName
Set tfile = tfolder.CreateTextFile(tname)
Set CreateTempFile = tfile
End Function
Description
Syntax
object.IsReady
The object is always a Drive object.
Remarks
Function ShowDriveInfo(drvpath)
Dim fso, d, s, t
Set fso = CreateObject("Scripting.FileSystemObject")
Set d = fso.GetDrive(drvpath)
Select Case d.DriveType
Case 0: t = "Unknown"
Case 1: t = "Removable"
Case 2: t = "Fixed"
Case 3: t = "Network"
Case 4: t = "CD-ROM"
Case 5: t = "RAM Disk"
End Select
s = "Drive " & d.DriveLetter & ": - " & t
If d.IsReady Then
s = s & "<BR>" & "Drive is Ready."
Else
s = s & "<BR>" & "Drive is not Ready."
End If
ShowDriveInfo = s
End Function
Microsoft® Visual Basic® Scripting Edition
Description
Returns True if the specified folder is the root folder; False if it is not.
Syntax
object.IsRootFolder
The object is always a Folder object.
Remarks
Function DisplayLevelDepth(pathspec)
Dim fso, f, n
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(pathspec)
If f.IsRootFolder Then
DisplayLevelDepth = "The specified folder is the root folder."
Else
Do Until f.IsRootFolder
Set f = f.ParentFolder
n = n + 1
Loop
DisplayLevelDepth = "The specified folder is nested " & n & " levels deep
End If
End Function
Microsoft® Visual Basic® Scripting Edition Item Scripting Run-Time Reference
Version 2
Property
See Also Applies To
Description
Syntax
object.Item(key) [= newitem]
The Item property has the following parts:
Part Description
Required. Always the name of a collection or
object
Dictionary object.
Required. Key associated with the item being retrieved
key
or added.
Optional. Used for Dictionary object only; no
newitem application for collections. If provided, newitem is the
new value associated with the specified key.
Remarks
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 return an existing
item, a new key is created and its corresponding item is left empty.
The following example illustrates the use of the Item property:
Function ItemDemo
Dim d ' Create some variables.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens" ' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
ItemDemo = d.Item("c") ' Get the item.
End Function
Microsoft® Visual Basic® Scripting Edition Items Scripting Run-Time Reference
Version 2
Method
See Also Applies to
Description
Syntax
object.Items
The object is always the name of a Dictionary object.
Remarks
Function DicDemo
Dim a, d, i, s ' Create some variables.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens" ' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
a = d.Items ' Get the items.
For i = 0 To d.Count -1 ' Iterate the array.
s = s & a(i) & "<BR>" ' Create return string.
Next
DicDemo = s
End Function
Microsoft® Visual Basic® Scripting Edition Key Scripting Run-Time Reference
Version 2
Property
See Also Applies to
Description
Syntax
object.Key(key) = newkey
The Key property has the following parts:
Part Description
object Required. Always the name of a Dictionary object.
key Required. Key value being changed.
newkey Required. New value that replaces the specified key.
Remarks
If key is not found when changing a key, a run-time error will occur.
The following example illustrates the use of the Key property:
Function DicDemo
Dim d ' Create some variables.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens" ' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
d.Key("c") = "d" ' Set key for "c" to "d".
DicDemo = d.Item("d") ' Return associate item.
End Function
Microsoft® Visual Basic® Scripting Edition Keys Scripting Run-Time Reference
Version 2
Method
See Also Applies to
Description
Syntax
object.Keys
The object is always the name of a Dictionary object.
Remarks
Function DicDemo
Dim a, d, i ' Create some variables.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens" ' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
a = d.Keys ' Get the keys.
For i = 0 To d.Count -1 ' Iterate the array.
s = s & a(i) & "<BR>" ' Return results.
Next
DicDemo = s
End Function
Microsoft® Visual Basic® Scripting Edition Line Scripting Run-Time Reference
Version 2
Property
See Also Applies to
Description
Syntax
object.Line
The object is always the name of a TextStream object.
Remarks
After a file is initially opened and before anything is written, Line is equal
to 1.
The following example illustrates use of the Line property:
Function GetLine
Const ForReading = 1, ForWriting = 2
Dim fso, f, ra
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
f.Write "Hello world!" & vbCrLf & "VB Script is fun!" & vbCrLf
Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
ra = f.ReadAll
GetLine = f.Line
End Function
Microsoft® Visual Basic® Scripting Edition Move Scripting Run-Time Reference
Version 3
Method
See Also Applies To
Description
Syntax
object.Move destination
The Move method syntax has these parts:
Part Description
Required. Always the name of a File or Folder
object
object.
Required. Destination where the file or folder is to
destination
be moved. Wildcard characters are not allowed.
Remarks
Description
Syntax
Part Description
object Required. Always the name of a FileSystemObject.
Required. The path to the file or files to be moved.
source The source argument string can contain wildcard
characters in the last path component only.
Required. The path where the file or files are to be
destination moved. The destination argument can't contain
wildcard characters.
Remarks
If destination does not exist, the file gets moved. This is the usual case.
If destination is an existing file, an error occurs.
If destination is a directory, an error occurs.
An error also occurs if a wildcard character that is used in source doesn't
match any files. The MoveFile method stops on the first error it encounters.
No attempt is made to roll back any changes made before the error occurs.
The following example illustrates use of the MoveFile method:
Sub MoveAFile(Drivespec)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
fso.MoveFile Drivespec, "c:\windows\desktop\"
End Sub
Description
Syntax
Part Description
object Required. Always the name of a FileSystemObject.
Required. The path to the folder or folders to be
source moved. The source argument string can contain
wildcard characters in the last path component only.
Required. The path where the folder or folders are to
destination be moved. The destination argument can't contain
wildcard characters.
Remarks
If destination does not exist, the folder gets moved. This is the usual
case.
If destination is an existing file, an error occurs.
If destination is a directory, an error occurs.
Sub MoveAFolder(Drivespec)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
fso.MoveFolder Drivespec, "c:\windows\desktop\"
End Sub
Description
Syntax
object.Name [= newname]
The Name property has these parts:
Part Description
object Required. Always the name of a File or Folder object.
Optional. If provided, newname is the new name of
newname
the specified object.
Remarks
Function ShowFileAccessInfo(filespec)
Dim fso, f, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(filespec)
s = f.Name & " on Drive " & UCase(f.Drive) & "<BR>"
s = s & "Created: " & f.DateCreated & "<BR>"
s = s & "Last Accessed: " & f.DateLastAccessed & "<BR>"
s = s & "Last Modified: " & f.DateLastModified
ShowFileAccessInfo = s
End Function
Microsoft® Visual Basic® Scripting Edition
Description
Opens a specified file and returns a TextStream object that can be used to
read from, write to, or append to the file.
Syntax
object.OpenAsTextStream([iomode, [format]])
The OpenAsTextStream method syntax has these parts:
Part Description
object Required. Always the name of a File object.
Optional. Indicates input/output mode. Can be one of
iomode three constants: ForReading, ForWriting, or
ForAppending.
Optional. One of three Tristate values used to indicate
format the format of the opened file. If omitted, the file is
opened as ASCII.
Settings
Remarks
Function TextStreamTest
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Const TristateUseDefault = -2, TristateTrue = -1, TristateF
Dim fso, f, ts
Set fso = CreateObject("Scripting.FileSystemObject")
fso.CreateTextFile "test1.txt" ' Create a file.
Set f = fso.GetFile("test1.txt")
Set ts = f.OpenAsTextStream(ForWriting, TristateUseDefa
ts.Write "Hello World"
ts.Close
Set ts = f.OpenAsTextStream(ForReading, TristateUseDef
TextStreamTest = ts.ReadLine
ts.Close
End Function
Microsoft® Visual Basic® Scripting Edition
Description
Opens a specified file and returns a TextStream object that can be used to
read from, write to, or append to the file.
Syntax
Part Description
object Required. Always the name of a FileSystemObject.
Required. String expression that identifies the file to
filename
open.
Optional. Indicates input/output mode. Can be one of
iomode three constants: ForReading, ForWriting, or
ForAppending.
Optional. Boolean value that indicates whether a new
file can be created if the specified filename doesn't
create
exist. The value is True if a new file is created; False
if it isn't created. The default is False.
Optional. One of three Tristate values used to indicate
format the format of the opened file. If omitted, the file is
opened as ASCII.
Settings
Remarks
The following code illustrates the use of the OpenTextFile method to open
a file for writing text:
Sub OpenTextFileTest
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
f.Write "Hello world!"
f.Close
End Sub
Microsoft® Visual Basic® Scripting Edition
Description
Returns the folder object for the parent of the specified file or folder. Read-
only.
Syntax
object.ParentFolder
The object is always a File or Folder object.
Remarks
The following code illustrates the use of the ParentFolder property with a
file:
Function ShowFileAccessInfo(filespec)
Dim fso, f, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(filespec)
s = UCase(f.Name) & " in " & UCase(f.ParentFolder) & "<BR>"
s = s & "Created: " & f.DateCreated & "<BR>"
s = s & "Last Accessed: " & f.DateLastAccessed & "<BR>"
s = s & "Last Modified: " & f.DateLastModified
ShowFileAccessInfo = s
End Function
Microsoft® Visual Basic® Scripting Edition Path Scripting Run-Time Reference
Version 3
Property
See Also Applies To
Description
Syntax
object.Path
The object is always a File, Folder, or Drive object.
Remarks
For drive letters, the root drive is not included. For example, the path for
the C drive is C:, not C:\.
The following code illustrates the use of the Path property with a File object:
Function ShowFileAccessInfo(filespec)
Dim fso, d, f, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(filespec)
s = UCase(f.Path) & "<BR>"
s = s & "Created: " & f.DateCreated & "<BR>"
s = s & "Last Accessed: " & f.DateLastAccessed & "<BR>"
s = s & "Last Modified: " & f.DateLastModified
ShowFileAccessInfo = s
End Function
Microsoft® Visual Basic® Scripting Edition Read Scripting Run-Time Reference
Version 2
Method
See Also Applies to
Description
Syntax
object.Read(characters)
The Read method syntax has these parts:
Part Description
object Required. Always the name of a TextStream object.
Required. Number of characters you want to read
characters
from the file.
Remarks
The following example illustrates how to use the Read method to read five
characters from a file and return the resulting string:
Function ReadTextFileTest
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim fso, f, Msg
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True
f.Write "Hello world!"
Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
ReadTextFileTest = f.Read(5)
End Function
Microsoft® Visual Basic® Scripting Edition ReadAll Scripting Run-Time Reference
Version 2
Method
See Also Applies to
Description
Syntax
object.ReadAll
The object is always the name of a TextStream object.
Remarks
For large files, using the ReadAll method wastes memory resources. Other
techniques should be used to input a file, such as reading a file line by line.
Function ReadAllTextFile
Const ForReading = 1, ForWriting = 2
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
f.Write "Hello world!"
Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
ReadAllTextFile = f.ReadAll
End Function
Microsoft® Visual Basic® Scripting Edition
Scripting Run-Time Reference
ReadLine Method Version 2
Description
Reads an entire line (up to, but not including, the newline character) from a
TextStream file and returns the resulting string.
Syntax
object.ReadLine
The object argument is always the name of a TextStream object.
Remarks
The following example shows how to use the ReadLine method to read a
line from a TextStream file and return the string:
Function ReadLineTextFile
Const ForReading = 1, ForWriting = 2
Dim fso, MyFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
MyFile.WriteLine "Hello world!"
MyFile.WriteLine "The quick brown fox"
MyFile.Close
Set MyFile = fso.OpenTextFile("c:\testfile.txt", ForReading)
ReadLineTextFile = MyFile.ReadLine ' Returns "Hello world!"
End Function
Microsoft® Visual Basic® Scripting Edition Remove Scripting Run-Time Reference
Version 2
Method
See Also Applies to
Description
Syntax
object.Remove(key)
The Remove method syntax has these parts:
Part Description
object Required. Always the name of a Dictionary object.
Required. Key associated with the key, item pair you want
key
to remove from the Dictionary object.
Remarks
An error occurs if the specified key, item pair does not exist.
The following code illustrates use of the Remove method:
Description
The RemoveAll method removes all key, item pairs from a Dictionary
object.
Syntax
object.RemoveAll
The object is always the name of a Dictionary object.
Remarks
Description
Syntax
object.RootFolder
The object is always a Drive object.
Remarks
All the files and folders contained on the drive can be accessed using the
returned Folder object.
The following example illustrates the use of the RootFolder property:
Function ShowRootFolder(drvspec)
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetDrive(drvspec)
ShowRootFolder = f.RootFolder
End Function
Microsoft® Visual Basic® Scripting Edition
Description
Returns the decimal serial number used to uniquely identify a disk volume.
Syntax
object.SerialNumber
The object is always a Drive object.
Remarks
You can use the SerialNumber property to ensure that the correct disk is
inserted in a drive with removable media.
The following code illustrates the use of the SerialNumber property:
Function ShowDriveInfo(drvpath)
Dim fso, d, s, t
Set fso = CreateObject("Scripting.FileSystemObject")
Set d = fso.GetDrive(fso.GetDriveName(fso.GetAbsolutePathName(drvpath
Select Case d.DriveType
Case 0: t = "Unknown"
Case 1: t = "Removable"
Case 2: t = "Fixed"
Case 3: t = "Network"
Case 4: t = "CD-ROM"
Case 5: t = "RAM Disk"
End Select
s = "Drive " & d.DriveLetter & ": - " & t
s = s & "<BR>" & "SN: " & d.SerialNumber
ShowDriveInfo = s
End Function
Microsoft® Visual Basic® Scripting Edition
Description
Syntax
object.ShareName
The object is always a Drive object.
Remarks
Function ShowDriveInfo(drvpath)
Dim fso, d
Set fso = CreateObject("Scripting.FileSystemObject")
Set d = fso.GetDrive(fso.GetDriveName(fso.GetAbsolutePathName(drvpath
ShowDriveInfo = "Drive " & d.DriveLetter & ": - " & d.ShareName
End Function
Microsoft® Visual Basic® Scripting Edition
Description
Returns the short name used by programs that require the earlier 8.3 naming
convention.
Syntax
object.ShortName
The object is always a File or Folder object.
Remarks
The following code illustrates the use of the ShortName property with a
File object:
Function ShowShortName(filespec)
Dim fso, f, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(filespec)
s = "The short name for " & UCase(f.Name) & "<BR>"
s = s & "is: " & f.ShortName
ShowShortName = s
End Function
Microsoft® Visual Basic® Scripting Edition
Description
Returns the short path used by programs that require the earlier 8.3 file
naming convention.
Syntax
object.ShortPath
The object is always a File or Folder object.
Remarks
The following code illustrates the use of the ShortName property with a
File object:
Function ShowShortPath(filespec)
Dim fso, f, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(filespec)
s = "The short path for " & UCase(f.Name) & "<BR>"
s = s & "is: " & f.ShortPath
ShowShortPath = s
End Function
Microsoft® Visual Basic® Scripting Edition Size Scripting Run-Time Reference
Version 3
Property
See Also Applies To
Description
For files, returns the size, in bytes, of the specified file. For folders, returns
the size, in bytes, of all files and subfolders contained in the folder.
Syntax
object.Size
The object is always a File or Folder object.
Remarks
The following code illustrates the use of the Size property with a Folder
object:
Function ShowFolderSize(filespec)
Dim fso, f, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(filespec)
s = UCase(f.Name) & " uses " & f.size & " bytes."
ShowFolderSize = s
End Function
Microsoft® Visual Basic® Scripting Edition Skip Scripting Run-Time Reference
Version 2
Method
See Also Applies To
Description
Syntax
object.Skip(characters)
The Skip method syntax has these parts:
Part Description
object Required. Always the name of a TextStream object.
Required. Number of characters to skip when
characters
reading a file.
Remarks
Function SkipTextFile
Const ForReading = 1, ForWriting = 2
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True
f.Write "Hello world!"
Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
f.Skip(6)
SkipTextFile = f.ReadLine
End Function
Microsoft® Visual Basic® Scripting Edition
Scripting Run-Time Reference
SkipLine Method Version 2
Description
Syntax
object.SkipLine
The object is always the name of a TextStream object.
Remarks
Function SkipLineInFile
Const ForReading = 1, ForWriting = 2
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
f.Write "Hello world!" & vbCrLf & "VB Script is fun!"
Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
f.SkipLine
SkipLineInFile = f.ReadLine
End Function
Microsoft® Visual Basic® Scripting Edition
These constants are only available when your project has an explicit reference to
the appropriate type library containing these constant definitions. For VBScript,
you must explicitly declare these constants in your code.
Description
Syntax
object.SubFolders
The object is always a Folder object.
Remarks
Function ShowFolderList(folderspec)
Dim fso, f, f1, s, sf
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(folderspec)
Set sf = f.SubFolders
For Each f1 in sf
s = s & f1.name
s = s & "<BR>"
Next
ShowFolderList = s
End Function
Microsoft® Visual Basic® Scripting Edition
Scripting Run-Time Reference
TextStream Object Version 2
Description
Remarks
In the following code, a is the TextStream object returned by the CreateTextFile method on the
FileSystemObject:
Description
Syntax
object.TotalSize
The object is always a Drive object.
Remarks
Function ShowSpaceInfo(drvpath)
Dim fso, d, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set d = fso.GetDrive(fso.GetDriveName(fso.GetAbsolutePathName(drvpath
s = "Drive " & d.DriveLetter & ":"
s = s & vbCrLf
s = s & "Total Size: " & FormatNumber(d.TotalSize/1024, 0) & " Kbytes"
s = s & vbCrLf
s = s & "Available: " & FormatNumber(d.AvailableSpace/1024, 0) & " Kbyt
ShowSpaceInfo = s
End Function
Microsoft® Visual Basic® Scripting Edition Type Scripting Run-Time Reference
Version 3
Property
See Also Applies To
Description
Returns information about the type of a file or folder. For example, for files
ending in .TXT, "Text Document" is returned.
Syntax
object.Type
The object is always a File or Folder object.
Remarks
The following code illustrates the use of the Type property to return a
folder type. In this example, try providing the path of the Recycle Bin or
other unique folder to the procedure.
Function ShowFolderType(filespec)
Dim fso, f, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(filespec)
s = UCase(f.Name) & " is a " & f.Type
ShowFolderType = s
End Function
Microsoft® Visual Basic® Scripting Edition
Description
Syntax
object.VolumeName [= newname]
The VolumeName property has these parts:
Part Description
object Required. Always the name of a Drive object.
Optional. If provided, newname is the new name of
newname
the specified object.
Remarks
Function ShowVolumeInfo(drvpath)
Dim fso, d, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set d = fso.GetDrive(fso.GetDriveName(fso.GetAbsolutePathName(drvpath
s = "Drive " & d.DriveLetter & ": - " & d.VolumeName
ShowVolumeInfo = s
End Function
Microsoft® Visual Basic® Scripting Edition Write Scripting Run-Time Reference
Version 2
Method
See Also Applies to
Description
Syntax
object.Write(string)
The Write method syntax has these parts:
Part Description
object Required. Always the name of a TextStream object.
string Required. The text you want to write to the file.
Remarks
Function WriteToFile
Const ForReading = 1, ForWriting = 2
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True
f.Write "Hello world!"
Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
WriteToFile = f.ReadLine
End Function
Microsoft® Visual Basic® Scripting Edition
Description
Syntax
object.WriteBlankLines(lines)
The WriteBlankLines method syntax has these parts:
Part Description
object Required. Always the name of a TextStream object.
Required. Number of newline characters you want to
lines
write to the file.
Remarks
Function WriteBlankLinesToFile
Const ForReading = 1, ForWriting = 2
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
f.WriteBlankLines 2
f.WriteLine "Hello World!"
Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
WriteBlankLinesToFile = f.ReadAll
End Function
Microsoft® Visual Basic® Scripting Edition
Scripting Run-Time Reference
WriteLine Method Version 2
Description
Syntax
object.WriteLine([string])
The WriteLine method syntax has these parts:
Part Description
object Required. Always the name of a TextStream object.
Optional. The text you want to write to the file. If
string
omitted, a newline character is written to the file.
Remarks
Function WriteLineToFile
Const ForReading = 1, ForWriting = 2
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
f.WriteLine "Hello world!"
f.WriteLine "VBScript is fun!"
Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
WriteLineToFile = f.ReadAll
End Function
Copyright
Information in this document is subject to change without notice. The names of companies, products,
people, characters, and/or data mentioned herein are fictitious and are in no way intended to represent any
real individual, company, product, or event, unless otherwise noted. Complying with all applicable
copyright laws is the responsibility of the user. No part of this document may be reproduced or transmitted
in any form or by any means, electronic or mechanical, for any purpose, without the express written
permission of Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights
covering subject matter in this document. Except as expressly provided in any written license agreement
from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks,
copyrights, or other intellectual property.
Microsoft, MS, MS-DOS, ActiveX, JScript, Microsoft Press, Visual Basic, Windows, Windows NT, Win32,
and Win32s are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or
other countries.
Other product and company names mentioned herein may be the trademarks of their respective owners.
Microsoft® Visual Basic® Scripting Edition
Language Reference
InStrRev Function Version 2
See Also
Description
Returns the position of an occurrence of one string within another, from the
end of string.
Syntax
Part Description
string1 Required. String expression being searched.
string2 Required. String expression being searched for.
Optional. Numeric expression that sets the starting
position for each search. If omitted, -1 is used, which
start
means that the search begins at the last character
position. If start contains Null, an error occurs.
Optional. Numeric value indicating the kind of
comparison to use when evaluating substrings. If
compare
omitted, a binary comparison is performed. See
Settings section for values.
Settings
If InStrRev returns
string1 is zero-length 0
string1 is Null Null
string2 is zero-length start
string2 is Null Null
string2 is not found 0
string2 is found within string1 Position at which match is found
start > Len(string2) 0
Remarks
Note The syntax for the InStrRev function is not the same as the syntax for the InStr
function.
Microsoft® Visual Basic® Scripting Edition Abs
Language Reference
Function
See Also
Sgn Function
Microsoft® Visual Basic® Scripting Edition
Language Reference
VBScript Glossary
ActiveX control
An object that you place on a form to enable or enhance a user's interaction with an application.
ActiveX controls have events and can be incorporated into other controls. The controls have an .ocx
file name extension.
ActiveX object
An object that is exposed to other applications or programming tools through Automation interfaces.
argument
A constant, variable, or expression passed to a procedure.
array
A set of sequentially indexed elements having the same type of data. Each element of an array has a
unique identifying index number. Changes made to one element of an array do not affect the other
elements.
Automation object
An object that is exposed to other applications or programming tools through Automation interfaces.
bitwise comparison
A bit-by-bit comparison of identically positioned bits in two numeric expressions.
Boolean expression
An expression that evaluates to either True or False.
by reference
A way of passing the address, rather than the value, of an argument to a procedure. This allows the
procedure to access the actual variable. As a result, the variable's actual value can be changed by the
procedure to which it is passed.
by value
A way of passing the value, rather than the address, of an argument to a procedure. This allows the
procedure to access a copy of the variable. As a result, the variable's actual value can't be changed by
the procedure to which it is passed.
character code
A number that represents a particular character in a set, such as the ASCII character set.
class
The formal definition of an object. The class acts as the template from which an instance of an object
is created at run time. The class defines the properties of the object and the methods used to control
the object's behavior.
class module
A module containing the definition of a class (its property and method definitions).
collection
An object that contains a set of related objects. An object's position in the collection can change
whenever a change occurs in the collection; therefore, the position of any specific object in the
collection may vary.
comment
Text added to code by a programmer that explains how the code works. In Visual Basic Scripting
Edition, a comment line generally starts with an apostrophe ('), or you can use the keyword Rem
followed by a space.
comparison operator
A character or symbol indicating a relationship between two or more values or expressions. These
operators include less than (<), less than or equal to (<=), greater than (>), greater than or equal to
(>=), not equal (<>), and equal (=).
Is is also a comparison operator, but it is used exclusively for determining if one object reference is
the same as another.
constant
A named item that retains a constant value throughout the execution of a program. Constants can be
used anywhere in your code in place of actual values. A constant can be a string or numeric literal,
another constant, or any combination that includes arithmetic or logical operators except Is and
exponentiation. For example:
Const A = "MyString"
data ranges
Each Variant subtype has a specific range of allowed values:
Subtype Range
Byte 0 to 255.
Boolean True or False.
Integer -32,768 to 32,767.
Long -2,147,483,648 to 2,147,483,647.
-3.402823E38 to -1.401298E-45 for negative values;
Single
1.401298E-45 to 3.402823E38 for positive values.
-1.79769313486232E308 to -4.94065645841247E-
Double 324 for negative values; 4.94065645841247E-324 to
1.79769313486232E308 for positive values.
-922,337,203,685,477.5808 to
Currency
922,337,203,685,477.5807.
Date January 1, 100 to December 31, 9999, inclusive.
Object Any Object reference.
Variable-length strings may range in length from 0 to
String
approximately 2 billion characters.
date expression
Any expression that can be interpreted as a date. This includes any combination of date literals,
numbers that look like dates, strings that look like dates, and dates returned from functions. A date
expression is limited to numbers or strings, in any combination, that can represent a date from
January 1, 100 through December 31, 9999.
Dates are stored as part of a real number. Values to the left of the decimal represent the date; values
to the right of the decimal represent the time. Negative numbers represent dates prior to December
30, 1899.
date literal
Any sequence of characters with a valid format that is surrounded by number signs (#). Valid formats
include the date format specified by the locale settings for your code or the universal date format. For
example, #12/31/99# is the date literal that represents December 31, 1999, where English-U.S. is the
locale setting for your application.
VBScript always interprets a date literal as US-ENGLISH if it is possible to do so. If a date literal
cannot be interpreted as a date, an error occurs.
date separators
Characters used to separate the day, month, and year when date values are formatted.
Empty
A value that indicates that no beginning value has been assigned to a variable. Empty variables are 0
in a numeric context, or zero-length in a string context.
error number
A whole number in the range 0 to 65,535, inclusive, that corresponds to the Number property of the
Err object. When combined with the Name property of the Err object, this number represents a
particular error message.
expression
A combination of keywords, operators, variables, and constants that yield a string, number, or object.
An expression can perform a calculation, manipulate characters, or test data.
intrinsic constant
A constant provided by an application. Because you can't disable intrinsic constants, you can't create
a user-defined constant with the same name.
keyword
A word or symbol recognized as part of the VBScript language; for example, a statement, function
name, or operator.
locale
The set of information that corresponds to a given language and country/region. A locale affects the
language of predefined programming terms and locale-specific settings. There are two contexts
where locale information is important:
The code locale affects the language of terms such as keywords and defines locale-specific
settings such as the decimal and list separators, date formats, and character sorting order.
The system locale affects the way locale-aware functionality behaves, for example, when you
display numbers or convert strings to dates. You set the system locale using the Control Panel
utilities provided by the operating system.
Nothing
The special value that indicates that an object variable is no longer associated with any actual object.
Null
A value indicating that a variable contains no valid data. Null is the result of:
An explicit assignment of Null to a variable.
numeric expression
Any expression that can be evaluated as a number. Elements of the expression can include any
combination of keywords, variables, constants, and operators that result in a number.
object type
A type of object exposed by an application, for example, Application, File, Range, and Sheet. Refer
to the application's documentation (Microsoft Excel, Microsoft Project, Microsoft Word, and so on)
for a complete listing of available objects.
pi
Pi is a mathematical constant equal to approximately 3.1415926535897932.
Private
Variables that are visible only to the script in which they are declared.
procedure
A named sequence of statements executed as a unit. For example, Function and Sub are types of
procedures.
procedure level
Describes statements located within a Function or Sub procedure. Declarations are usually listed
first, followed by assignments and other executable code. For example:
property
A named attribute of an object. Properties define object characteristics such as size, color, and screen
location, or the state of an object, such as enabled or disabled.
Public
Variables declared using the Public Statement are visible to all procedures in all modules in all
applications.
run time
The time when code is running. During run time, you can't edit the code.
run-time error
An error that occurs when code is running. A run-time error results when a statement attempts an
invalid operation.
scope
Defines the visibility of a variable, procedure, or object. For example, a variable declared as Public
is visible to all procedures in all modules. Variables declared in procedures are visible only within the
procedure and lose their value between calls.
SCODE
A long integer value that is used to pass detailed information to the caller of an interface member or
API function. The status codes for OLE interfaces and APIs are defined in FACILITY_ITF.
script level
Any code outside a procedure is referred to as script-level code.
seed
An initial value used to generate pseudorandom numbers. For example, the Randomize statement
creates a seed number used by the Rnd function to create unique pseudorandom number sequences.
string comparison
A comparison of two sequences of characters. Unless specified in the function making the
comparison, all string comparisons are binary. In English, binary comparisons are case-sensitive; text
comparisons are not.
string expression
Any expression that evaluates to a sequence of contiguous characters. Elements of a string expression
can include a function that returns a string, a string literal, a string constant, or a string variable.
type library
A file or component within another file that contains standard descriptions of exposed objects,
properties, and methods.
variable
A named storage location that can contain data that can be modified during program execution. Each
variable has a name that uniquely identifies it within its level of scope.
Variable names:
Information
The following table lists the version of Microsoft Visual Basic Scripting
Edition implemented by host applications.
VBScript Version
Host Application
1.0 2.0 3.0 4.0 5.0
Microsoft Internet Explorer 3.0 x
Microsoft Internet Information Server 3.0 x
Microsoft Internet Explorer 4.0 x
Microsoft Internet Information Server 4.0 x
Microsoft Windows Scripting Host 1.0 x
Microsoft Outlook 98 x
Microsoft Visual Studio 6.0 x
Microsoft Internet Explorer 5.0 x
Microsoft Internet Information Services 5.0 x
The following table lists VBScript language features and the version when
first introduced.
See Also
Class Statement
Dim Statement
Set Statement
Microsoft® Visual Basic® Scripting Edition Class Language Reference
Object
Events
Initialize Event
Terminate Event
Class
Microsoft® Visual Basic® Scripting Edition
Language Reference
Statement
See Also
Dim Statement
Function Statement
Private Statement
Property Get Statement
Property Let Statement
Property Set Statement
Public Statement
Set Statement
Sub Statement
Microsoft® Visual Basic® Scripting Edition Clear
Language Reference
Method
See Also
Description Property
Err Object
Number Property
On Error Statement
Raise Method
Source Property
Microsoft® Visual Basic® Scripting Edition Clear
Language Reference
Method
Applies To
Err Object
Microsoft® Visual Basic® Scripting Edition CLng
Language Reference
Function
See Also
CBool Function
CByte Function
CCur Function
CDate Function
CDbl Function
CInt Function
CSng Function
CStr Function
Int, Fix Functions
Microsoft® Visual Basic® Scripting Edition
Constants
See Also
Color Constants
Comparison Constants
Date Format Constants
Miscellaneous Constants
MsgBox Constants
String Constants
Tristate Constants
VarType Constants
Date
Microsoft® Visual Basic® Scripting Edition
Language Reference
Format Constants
See Also
Color Constants
Comparison Constants
Date and Time Constants
Miscellaneous Constants
MsgBox Constants
String Constants
Tristate Constants
VarType Constants
Microsoft® Visual Basic® Scripting Edition Date
Language Reference
Function
See Also
CDate Function
Now Function
Time Function
Microsoft® Visual Basic® Scripting Edition
See Also
DateDiff Function
DatePart Function
Microsoft® Visual Basic® Scripting Edition
See Also
DateAdd Function
DatePart Function
Microsoft® Visual Basic® Scripting Edition
See Also
DateAdd Function
DateDiff Function
Microsoft® Visual Basic® Scripting Edition
See Also
Replace Method
Test Method
Microsoft® Visual Basic® Scripting Edition Execute Language Reference
Method
Applies To
RegExp Object
Execute
Microsoft® Visual Basic® Scripting Edition
Language Reference
Statement
See Also
Eval Function
ExecuteGlobal Statement
Exit
Microsoft® Visual Basic® Scripting Edition
Language Reference
Statement
See Also
Do...Loop Statement
For Each...Next Statement
For...Next Statement
Function Statement
Sub Statement
Microsoft® Visual Basic® Scripting Edition Exp
Language Reference
Function
See Also
Derived Math Functions
Log Function
Microsoft® Visual Basic® Scripting Edition ^
Language Reference
Operator
See Also
Arithmetic Operators
Operator Precedence
Operator Summary
Microsoft® Visual Basic® Scripting Edition Filter
Language Reference
Function
See Also
Replace Function
Microsoft® Visual Basic® Scripting Edition
Statement
See Also
Do...Loop Statement
Exit Statement
For...Next Statement
While...Wend Statement
Microsoft® Visual Basic® Scripting Edition
See Also
IgnoreCase Property
Pattern Property
Microsoft® Visual Basic® Scripting Edition Global Language Reference
Property
Applies To
RegExp Object
Microsoft® Visual Basic® Scripting Edition Hex
Language Reference
Function
See Also
Oct Function
Microsoft® Visual Basic® Scripting Edition
See Also
Description Property
HelpContext Property
Number Property
Source Property
Microsoft® Visual Basic® Scripting Edition
Applies To
Err Object
Microsoft® Visual Basic® Scripting Edition Hour
Language Reference
Function
See Also
Day Function
Minute Function
Now Function
Second Function
Time Function
Microsoft® Visual Basic® Scripting Edition
See Also
Class Object
Class Statement
Terminate Event
Microsoft® Visual Basic® Scripting Edition
Applies To
Class Object
Microsoft® Visual Basic® Scripting Edition
See Also
MsgBox Function
Microsoft® Visual Basic® Scripting Edition InStr
Language Reference
Function
See Also
InStrRev Function
Microsoft® Visual Basic® Scripting Edition \
Language Reference
Operator
See Also
* Operator
/ Operator
Arithmetic Operators
Operator Precedence
Operator Summary
Microsoft® Visual Basic® Scripting Edition Is
Language Reference
Operator
See Also
Comparison Operators
Operator Precedence
Operator Summary
Microsoft® Visual Basic® Scripting Edition IsArray
Language Reference
Function
See Also
IsDate Function
IsEmpty Function
IsNull Function
IsNumeric Function
IsObject Function
VarType Function
Microsoft® Visual Basic® Scripting Edition IsDate
Language Reference
Function
See Also
CDate Function
IsArray Function
IsEmpty Function
IsNull Function
IsNumeric Function
IsObject Function
VarType Function
Microsoft® Visual Basic® Scripting Edition
See Also
IsArray Function
IsDate Function
IsNull Function
IsNumeric Function
IsObject Function
VarType Function
Microsoft® Visual Basic® Scripting Edition IsNull
Language Reference
Function
See Also
IsArray Function
IsDate Function
IsEmpty Function
IsNumeric Function
IsObject Function
VarType Function
Microsoft® Visual Basic® Scripting Edition
See Also
IsArray Function
IsDate Function
IsEmpty Function
IsNull Function
IsNumeric Function
Set Statement
VarType Function
Microsoft® Visual Basic® Scripting Edition Join
Language Reference
Function
See Also
Split Function
Microsoft® Visual Basic® Scripting Edition LBound
Language Reference
Function
See Also
Dim Statement
ReDim Statement
UBound Function
Microsoft® Visual Basic® Scripting Edition LCase
Language Reference
Function
See Also
UCase Function
Microsoft® Visual Basic® Scripting Edition Left
Language Reference
Function
See Also
Len Function
Mid Function
Right Function
Microsoft® Visual Basic® Scripting Edition Len
Language Reference
Function
See Also
InStr Function
Microsoft® Visual Basic® Scripting Edition Length Language Reference
Property
See Also
FirstIndex Property
Value Property
Microsoft® Visual Basic® Scripting Edition Length Language Reference
Property
Applies To
Match Object
Microsoft® Visual Basic® Scripting Edition Log
Language Reference
Function
See Also
Derived Math Functions
Exp Function
LTrim,
Microsoft® Visual Basic® Scripting Edition
Functions
See Also
Left Function
Right Function
Microsoft® Visual Basic® Scripting Edition Match
Language Reference
Object
See Also
Matches Collection
RegExp Object
Microsoft® Visual Basic® Scripting Edition Match
Language Reference
Object
Properties
FirstIndex Property
Length Property
Value Property
Microsoft® Visual Basic® Scripting Edition Matches
Language Reference
Collection
See Also
For Each...Next Statement
Match Object
RegExp Object
Microsoft® Visual Basic® Scripting Edition Matches
Language Reference
Collection
Properties
Count Property
Item Property
Microsoft® Visual Basic® Scripting Edition Mid
Language Reference
Function
See Also
Left Function
Len Function
LTrim, RTrim, and Trim Functions
Right Function
Microsoft® Visual Basic® Scripting Edition Minute
Language Reference
Function
See Also
Day Function
Hour Function
Now Function
Second Function
Time Function
Microsoft® Visual Basic® Scripting Edition
See Also
Dim Statement
Set Statement
Microsoft® Visual Basic® Scripting Edition Number
Language Reference
Property
See Also
Description Property
HelpContext Property
HelpFile Property
Err Object
Source Property
Error Messages
Microsoft® Visual Basic® Scripting Edition Number
Language Reference
Property
Applies To
Err Object
Microsoft® Visual Basic® Scripting Edition Oct
Language Reference
Function
See Also
Hex Function
On
Microsoft® Visual Basic® Scripting Edition
Language Reference
Error Statement
See Also
Err Object
Exit Statement
Microsoft® Visual Basic® Scripting Edition
See Also
Global Property
IgnoreCase Property
Microsoft® Visual Basic® Scripting Edition Pattern Language Reference
Property
Applies To
RegExp Object
Private
Microsoft® Visual Basic® Scripting Edition
Language Reference
Statement
See Also
Dim Statement
Public Statement
ReDim Statement
Set Statement
Microsoft® Visual Basic® Scripting Edition
See Also
Match Object
Matches Collection
Microsoft® Visual Basic® Scripting Edition RegExp Language Reference
Object
Methods
Execute Method
Replace Method
Test Method
Microsoft® Visual Basic® Scripting Edition RegExp Language Reference
Object
Properties
Global Property
IgnoreCase Property
Pattern Property
Microsoft® Visual Basic® Scripting Edition Replace
Language Reference
Function
See Also
Filter Function
Microsoft® Visual Basic® Scripting Edition Replace Language Reference
Method
See Also
Execute Method
Test Method
Microsoft® Visual Basic® Scripting Edition Replace Language Reference
Method
Applies To
RegExp Object
Microsoft® Visual Basic® Scripting Edition Right
Language Reference
Function
See Also
Left Function
Len Function
Mid Function
Microsoft® Visual Basic® Scripting Edition Rnd
Language Reference
Function
See Also
Randomize Statement
Microsoft® Visual Basic® Scripting Edition Round
Language Reference
Function
See Also
Int, Fix Functions
Microsoft® Visual Basic® Scripting Edition
See Also
Class Object
Class Statement
Initialize Event
Microsoft® Visual Basic® Scripting Edition
Applies To
Class Object
Microsoft® Visual Basic® Scripting Edition Test Language Reference
Method
See Also
Execute Method
Replace Method
Microsoft® Visual Basic® Scripting Edition Test Language Reference
Method
Applies To
RegExp Object
Microsoft® Visual Basic® Scripting Edition Time
Language Reference
Function
See Also
Date Function
Microsoft® Visual Basic® Scripting Edition
See Also
Randomize Statement
Microsoft® Visual Basic® Scripting Edition
See Also
FirstIndex Property
Length Property
Microsoft® Visual Basic® Scripting Edition Value Language Reference
Property
Applies To
Match Object
Microsoft® Visual Basic® Scripting Edition
See Also
IsArray Function
IsDate Function
IsEmpty Function
IsNull Function
IsNumeric Function
IsObject Function
TypeName Function
Microsoft® Visual Basic® Scripting Edition
See Also
Date Function
Day Function
Month Function
Now Function
Year Function
Microsoft® Visual Basic® Scripting Edition
Description
Syntax
ExecuteGlobal statement
The required statement argument is a string expression containing one or more statements for
execution. Include multiple statements in the statement argument, using colons or embedded line
breaks to separate them.
Remarks
All statements used with ExecuteGlobal are executed in the script's global namespace. This allows
code to be added to the program so that any procedure can access it. For example, a VBScript Class
statement can be executed at run time and functions can subsequently create new instances of the
class.
Adding procedures and classes at runtime can be useful, but also introduces the possibility of
overwriting existing global variables and functions at runtime. Because this can cause significant
programming problems, care should be exercised when using the ExecuteGlobal statement. If you
don�t need access to a variable or function outside of a procedure, use the Execute statement which
will only affect the namespace of the calling function.
Description
Syntax
GetLocale()
Remarks
The following example illustrates the use of the GetLocale function. To use this code, paste the
entire example between the <BODY>l; tags of a standard HTML page.
<script language="vbscript">
Dim currentLocale
' Get the current locale
currentLocale = GetLocale
Sub Button1_onclick
Dim original
original = SetLocale("en-gb")
mydate = CDate(UKDate.value)
' IE always sets the locale to US English so use the
' currentLocale variable to set the locale to US English
original = SetLocale(currentLocale)
USDate.value = FormatDateTime(mydate,vbShortDate)
End Sub
Sub button2_onclick
Dim original
original = SetLocale("de")
myvalue = CCur(GermanNumber.value)
original = SetLocale("en-gb")
USNumber.value = FormatCurrency(myvalue)
End Sub
</script>
Microsoft® Visual Basic® Scripting
Locale
Edition
ID Language Reference
Version 5
(LCID)
Chart
See Also
ar-
Arabic - U.A.E. 0x3801 14337 Hungarian hu 0x040E 1038
ae
ar-
Arabic - Bahrain 0x3C01 15361 Icelandic is 0x040F 1039
bh
Arabic - Algeria ar- 0x1401 5121 Indonesian in 0x0421 1057
dz
ar-
Arabic - Egypt 0x0C01 3073 Italian - Standard it 0x0410 1040
eg
ar-
Arabic - Jordan 0x2C01 11265 Japanese ja 0x0411 1041
jo
ar-
Arabic - Kuwait 0x3401 13313 Korean ko 0x0412 1042
kw
ar-
Arabic - Lebanon 0x3001 12289 Latvian lv 0x0426 1062
lb
ar-
Arabic - Libya 0x1001 4097 Lithuanian lt 0x0427 1063
ly
ar-
Arabic - Morocco 0x1801 6145 Macedonian mk 0x042F 1071
ma
ar-
Arabic - Oman 0x2001 8193 Malay - Malaysia ms 0x043E 1086
om
ar-
Arabic - Qatar 0x4001 16385 Maltese mt 0x043A 1082
qa
Arabic - Saudia ar- Norwegian -
Arabia sa 0x0401 1025 Bokmål no 0x0414 1044
ar-
Arabic - Syria 0x2801 10241 Polish pl 0x0415 1045
sy
ar- Portuguese -
Arabic - Tunisia 0x1C01 7169 pt 0x0816 2070
tn Standard
Romanian - ro-
Bulgarian bg 0x0402 1026 0x0818 2072
Moldova mo
Russian - ru-
Chinese zh 0x0004 4 0x0819 2073
Moldova mo
zh-
Chinese - PRC 0x0804 2052 Serbian - Cyrillic sr 0x0C1A 3098
cn
Chinese - Hong zh- 0x0C04 3076 Setsuana tn 0x0432 1074
Kong hk
Chinese - zh-
0x1004 4100 Slovenian sl 0x0424 1060
Singapore sg
zh-
Chinese - Taiwan 0x0404 1028 Slovak sk 0x041B 1051
tw
Spanish -
Czech cs 0x0405 1029 es 0x040A 1034
Standard
Spanish - es-
Danish da 0x0406 1030 0x2C0A 11274
Argentina ar
es-
Dutch nl 0x0413 1043 Spanish - Bolivia 0x400A 16394
bo
nl- es-
Dutch - Belgium 0x0813 2067 Spanish - Chile 0x340A 13322
be cl
Spanish - es-
English en 0x0009 9 0x240A 9226
Columbia co
en- es-
English - Trinidad 0x2C09 11273 Spanish - Panama 0x180A 6154
tt pa
Spanish - es-
Estonian et 0x0425 1061 Paraguay py 0x3C0A 15370
Spanish - El es-
Farsi fa 0x0429 1065 Salvador sv 0x440A 17418
Spanish - es-
Finnish fi 0x040B 1035 0x380A 14346
Uruguay uy
Spanish - es-
Faeroese fo 0x0438 1080 0x200A 8202
Venezuela ve
fr-
French - Belgium 0x080C 2060 Swedish sv 0x041D 1053
be
fr- sv-
French - Canada 0x0C0C 3084 Swedish - Finland 0x081D 2077
ca fi
French - fr-
0x140C 5132 Thai th 0x041E 1054
Luxembourg lu
French - fr-
0x100C 4108 Turkish tr 0x041F 1055
Switzerland ch
German -
Standard de 0x0407 1031 Ukranian uk 0x0422 1058
German - de-
Austrian at 0x0C07 3079 Urdu - Pakistan ur 0x0420 1056
German - de-
0x1407 5127 Vietnamese vi 0x042A 1066
Lichtenstein li
German - de-
0x1007 4103 Xhosa xh 0x0434 1076
Luxembourg lu
German - de-
0x0807 2055 Yiddish ji 0x043D 1085
Switzerland ch
Description
Syntax
SetLocale(lcid)
The lcid argument can be any valid 32-bit value or short string that uniquely
identifies a geographical locale. Recognized values can be found in the
Locale ID chart.
Remarks
If lcid is zero, the locale is set to match the current system setting.
The following example illustrates the use of the SetLocale function. To use
this code, paste the entire example between the <BODY> tags of a standard
HTML page.
Enter Date in UK format: <input type="text" id="UKDate"
Here's the US equivalent: <input type="text" id="USdate" s
<input type="button" value="Convert" id="button1"><p>
Enter a price in German: <input type="text" id="Ge
<p>
Here's the UK equivalent: <input type="text" id="USNumb
<input type="button" value="Convert" id="button2"><p>
<script language="vbscript">
Dim currentLocale
' Get the current locale
currentLocale = GetLocale
Sub Button1_onclick
Dim original
original = SetLocale("en-gb")
mydate = CDate(UKDate.value)
' IE always sets the locale to US English so use the
' currentLocale variable to set the locale to US English
original = SetLocale(currentLocale)
USDate.value = FormatDateTime(mydate,vbShortDate)
End Sub
Sub button2_onclick
Dim original
original = SetLocale("de")
myvalue = CCur(GermanNumber.value)
original = SetLocale("en-gb")
USNumber.value = FormatCurrency(myvalue)
End Sub
</script>
Microsoft® Visual Basic® Scripting Edition Add
Method Scripting Run-Time Reference
(Dictionary)
See Also
Add Method (Folders)
Exists Method
Items Method
Keys Method
Remove Method
RemoveAll Method
Microsoft® Visual Basic® Scripting Edition Add
Method Scripting Run-Time Reference
(Dictionary)
Applies To
Dictionary Object
Add
Microsoft® Visual Basic® Scripting Edition
Scripting Run-Time Reference
Method (Folders)
See Also
Add Method (Dictionary)
Add
Microsoft® Visual Basic® Scripting Edition
Scripting Run-Time Reference
Method (Folders)
Applies To
Folders Collection
Microsoft® Visual Basic® Scripting Edition
See Also
GetAbsolutePathName Method
GetBaseName Method
GetDriveName Method
GetExtensionName Method
GetFileName Method
GetParentFolderName Method
GetTempName Method
Microsoft® Visual Basic® Scripting Edition
Applies To
FileSystemObject Object
Microsoft® Visual Basic® Scripting Edition Close
Scripting Run-Time Reference
Method
See Also
Read Method
ReadAll Method
ReadLine Method
Skip Method
SkipLine Method
Write Method
WriteLine Method
WriteBlankLines Method
Microsoft® Visual Basic® Scripting Edition Close
Scripting Run-Time Reference
Method
Applies To
TextStream Object
Microsoft® Visual Basic® Scripting Edition Column
Scripting Run-Time Reference
Property
See Also
AtEndOfLine Property
AtEndOfStream Property
Line Property
Microsoft® Visual Basic® Scripting Edition Column
Scripting Run-Time Reference
Property
Applies To
TextStream Object
Microsoft® Visual Basic® Scripting Edition
See Also
Copy Method
CopyFolder Method
CreateTextFile Method
DeleteFile Method
MoveFile Method
Microsoft® Visual Basic® Scripting Edition
Applies To
FileSystemObject Object
Microsoft® Visual Basic® Scripting Edition
See Also
CompareMode Property
Item Property
Key Property
Microsoft® Visual Basic® Scripting Edition Count Scripting Run-Time Reference
Property
Applies To
Dictionary Object
Drives Collection
Files Collection
Folders Collection
Matches Collection
Microsoft® Visual Basic® Scripting Edition
See Also
CopyFile Method
CreateTextFile Method
Delete Method
DeleteFolder Method
MoveFile Method
Microsoft® Visual Basic® Scripting Edition
See Also
FileSystemObject Object
TextStream Object
Microsoft® Visual Basic® Scripting Edition
Properties
CompareMode Property
Count Property
Item Property
Key Property
Microsoft® Visual Basic® Scripting Edition
Methods
Add Method (Dictionary)
Exists Method
Items Method
Keys Method
Remove Method
RemoveAll Method
Microsoft® Visual Basic® Scripting Edition Drive Scripting Run-Time Reference
Object
See Also
Drives Collection
File Object
Files Collection
Folder Object
Folders Collection
GetDrive Method
Microsoft® Visual Basic® Scripting Edition Drive Scripting Run-Time Reference
Object
Properties
AvailableSpace Property
DriveLetter Property
DriveType Property
FileSystem Property
FreeSpace Property
IsReady Property
Path Property
RootFolder Property
SerialNumber Property
ShareName Property
TotalSize Property
VolumeName Property
Microsoft® Visual Basic® Scripting Edition Drive Scripting Run-Time Reference
Object
Methods
The Drive object has no methods.
Microsoft® Visual Basic® Scripting Edition Drive Scripting Run-Time Reference
Property
See Also
Attributes Property
DateCreated Property
DateLastAccessed Property
DateLastModified Property
Files Property
IsRootFolder Property
Name Property
ParentFolder Property
Path Property
ShortName Property
ShortPath Property
Size Property
SubFolders Property
Type Property
Microsoft® Visual Basic® Scripting Edition Drive Scripting Run-Time Reference
Property
Applies To
File Object
Folder Object
Microsoft® Visual Basic® Scripting Edition
See Also
Drives Collection
Files Property
SubFolders Property
Microsoft® Visual Basic® Scripting Edition Drives Scripting Run-Time Reference
Property
Applies To
FileSystemObject Object
Microsoft® Visual Basic® Scripting Edition
Constants
See Also
Comparison Constants
DriveType Constants
File Attribute Constants
SpecialFolder Constants
Tristate Constants
Microsoft® Visual Basic® Scripting Edition
See Also
DriveExists Method
FolderExists Method
GetFile Method
GetFileName Method
Microsoft® Visual Basic® Scripting Edition
See Also
Drive Object
Drives Collection
Files Collection
Folder Object
Folders Collection
Microsoft® Visual Basic® Scripting Edition File Scripting Run-Time Reference
Object
Properties
Attributes Property
DateCreated Property
DateLastAccessed Property
DateLastModified Property
Drive Property
Name Property
ParentFolder Property
Path Property
ShortName Property
ShortPath Property
Size Property
Type Property
Microsoft® Visual Basic® Scripting Edition File Scripting Run-Time Reference
Object
Methods
Copy Method
Delete Method
Move Method
OpenAsTextStream Method
Microsoft® Visual Basic® Scripting Edition Files
Scripting Run-Time Reference
Collection
See Also
Drive Object
Drives Collection
File Object
Folder Object
Folders Collection
Microsoft® Visual Basic® Scripting Edition Files
Scripting Run-Time Reference
Collection
Properties
Count Property
Item Property
Microsoft® Visual Basic® Scripting Edition Files
Scripting Run-Time Reference
Collection
Methods
The Files collection has no methods.
Microsoft® Visual Basic® Scripting Edition Files Scripting Run-Time Reference
Property
See Also
Attributes Property
DateCreated Property
DateLastAccessed Property
DateLastModified Property
Drives Property
IsRootFolder Property
Name Property
ParentFolder Property
Path Property
ShortName Property
ShortPath Property
Size Property
SubFolders Property
Type Property
Microsoft® Visual Basic® Scripting Edition Files Scripting Run-Time Reference
Property
Applies To
Folder Object
Microsoft® Visual Basic® Scripting Edition
See Also
Drive Object
Drives Collection
File Object
Files Collection
Folders Collection
Microsoft® Visual Basic® Scripting Edition Folder Scripting Run-Time Reference
Object
Properties
Attributes Property
DateCreated Property
DateLastAccessed Property
DateLastModified Property
Drive Property
Files Property
IsRootFolder Property
Name Property
ParentFolder Property
Path Property
ShortName Property
ShortPath Property
Size Property
SubFolders Property
Type Property
Microsoft® Visual Basic® Scripting Edition Folder
Scripting Run-Time Reference
Object
Methods
Copy Method
Delete Method
Move Method
CreateTextFile Method
Microsoft® Visual Basic® Scripting Edition Folders
Scripting Run-Time Reference
Collection
See Also
Drive Object
Drives Collection
File Object
Files Collection
Folder Object
SubFolders Property
Microsoft® Visual Basic® Scripting Edition Folders
Scripting Run-Time Reference
Collection
Properties
Count Property
Item Property
Microsoft® Visual Basic® Scripting Edition Folders
Scripting Run-Time Reference
Collection
Methods
Add Method
Microsoft® Visual Basic® Scripting Edition
See Also
GetBaseName Method
GetDrive Method
GetDriveName Method
GetExtensionName Method
GetFile Method
GetFileName Method
GetFileVersion Method
GetFolder Method
GetParentFolderName Method
GetSpecialFolder Method
GetTempName Method
Microsoft® Visual Basic® Scripting Edition
Applies To
FileSystemObject Object
Microsoft® Visual Basic® Scripting Edition
See Also
GetAbsolutePathName Method
GetBaseName Method
GetDrive Method
GetDriveName Method
GetExtensionName Method
GetFileName Method
GetFileVersion Method
GetFolder Method
GetParentFolderName Method
GetSpecialFolder Method
GetTempName Method
Microsoft® Visual Basic® Scripting Edition GetFile Scripting Run-Time Reference
Method
Applies To
FileSystemObject Object
Microsoft® Visual Basic® Scripting Edition
See Also
GetAbsolutePathName Method
GetBaseName Method
GetDrive Method
GetDriveName Method
GetExtensionName Method
GetFile Method
GetFileName Method
GetFileVersion Method
GetFolder Method
GetSpecialFolder Method
GetTempName Method
Microsoft® Visual Basic® Scripting Edition
Applies To
FileSystemObject Object
Microsoft® Visual Basic® Scripting Edition
See Also
AvailableSpace Property
DriveLetter Property
DriveType Property
FileSystem Property
FreeSpace Property
Path Property
RootFolder Property
SerialNumber Property
ShareName Property
TotalSize Property
VolumeName Property
Microsoft® Visual Basic® Scripting Edition IsReady Scripting Run-Time Reference
Property
Applies To
Drive Object
Microsoft® Visual Basic® Scripting Edition
See Also
CompareMode Property
Count Property
Key Property
Microsoft® Visual Basic® Scripting Edition Item Scripting Run-Time Reference
Property
Applies To
Dictionary Object
Drives Collection
Files Collection
Folders Collection
Matches Collection
Microsoft® Visual Basic® Scripting Edition Items
Scripting Run-Time Reference
Method
See Also
Add Method (Dictionary)
Exists Method
Keys Method
Remove Method
RemoveAll Method
Microsoft® Visual Basic® Scripting Edition Items
Scripting Run-Time Reference
Method
Applies To
Dictionary Object
Microsoft® Visual Basic® Scripting Edition Key
Scripting Run-Time Reference
Property
See Also
CompareMode Property
Count Property
Item Property
Microsoft® Visual Basic® Scripting Edition Key
Scripting Run-Time Reference
Property
Applies To
Dictionary Object
Microsoft® Scripting Library - FileSystemObject
Glossary
array
A set of sequentially indexed elements having the same type of data. Each element of an array has a
unique identifying index number. Changes made to one element of an array do not affect the other
elements.
collection
An object that contains a set of related objects. An object's position in the collection can change
whenever a change occurs in the collection; therefore, the position of any specific object in the
collection may vary.
run-time error
An error that occurs when code is running. A run-time error results when a statement attempts an
invalid operation.
string expression
Any expression that evaluates to a sequence of contiguous characters. Elements of a string expression
can include a function that returns a string, a string literal, a string constant, or a string variable.
type library
A file or component within another file that contains standard descriptions of exposed objects,
properties, and methods.
Microsoft® Visual Basic® Scripting Edition Keys
Scripting Run-Time Reference
Method
See Also
Add Method (Dictionary)
Exists Method
Items Method
Remove Method
RemoveAll Method
Microsoft® Visual Basic® Scripting Edition Keys
Scripting Run-Time Reference
Method
Applies To
Dictionary Object
Microsoft® Visual Basic® Scripting Edition Line
Scripting Run-Time Reference
Property
See Also
AtEndOfStream Property
AtEndOfLine Property
Column Property
Microsoft® Visual Basic® Scripting Edition Line Scripting Run-Time Reference
Property Version
Applies To
TextStream Object
Microsoft® Visual Basic® Scripting Edition Move Scripting Run-Time Reference
Method
See Also
Copy Method
Delete Method
MoveFile Method
MoveFolder Method
OpenAsTextStream Method
Microsoft® Visual Basic® Scripting Edition Move Scripting Run-Time Reference
Method
Applies To
File Object
Folder Object
Microsoft® Visual Basic® Scripting Edition
See Also
Attributes Property
DateCreated Property
DateLastAccessed Property
DateLastModified Property
Drive Property
Files Property
IsRootFolder Property
ParentFolder Property
Path Property
ShortName Property
ShortPath Property
Size Property
SubFolders Property
Type Property
Microsoft® Visual Basic® Scripting Edition Name Scripting Run-Time Reference
Property
Applies To
File Object
Folder Object
Microsoft® Visual Basic® Scripting Edition
See Also
Attributes Property
AvailableSpace Property
DateCreated Property
DateLastAccessed Property
DateLastModified Property
Drive Property
DriveLetter Property
DriveType Property
Files Property
FileSystem Property
FreeSpace Property
IsReady Property
IsRootFolder Property
Name Property
ParentFolder Property
RootFolder Property
SerialNumber Property
ShareName Property
ShortName Property
ShortPath Property
Size Property
SubFolders Property
TotalSize Property
Type Property
VolumeName Property
Microsoft® Visual Basic® Scripting Edition Path Scripting Run-Time Reference
Property
Applies To
Drive Object
File Object
Folder Object
Microsoft® Visual Basic® Scripting Edition Read
Scripting Run-Time Reference
Method
See Also
Close Method
ReadAll Method
ReadLine Method
Skip Method
SkipLine Method
Write Method
WriteLine Method
WriteBlankLines Method
Microsoft® Visual Basic® Scripting Edition Read
Scripting Run-Time Reference
Method
Applies To
TextStream Object
Microsoft® Visual Basic® Scripting Edition ReadAll
Scripting Run-Time Reference
Method
See Also
Close Method
Read Method
ReadLine Method
Skip Method
SkipLine Method
Write Method
WriteLine Method
WriteBlankLines Method
Microsoft® Visual Basic® Scripting Edition ReadAll
Scripting Run-Time Reference
Method
Applies To
TextStream Object
Microsoft® Visual Basic® Scripting Edition
See Also
Close Method
Read Method
ReadAll Method
Skip Method
SkipLine Method
Write Method
WriteLine Method
WriteBlankLines Method
Microsoft® Visual Basic® Scripting Edition
Applies To
TextStream Object
Microsoft® Visual Basic® Scripting Edition Remove
Scripting Run-Time Reference
Method
See Also
Add Method (Dictionary)
Exists Method
Items Method
Keys Method
RemoveAll Method
Microsoft® Visual Basic® Scripting Edition Remove
Scripting Run-Time Reference
Method
Applies To
Dictionary Object
Microsoft® Visual Basic® Scripting Edition
See Also
Attributes Property
DateCreated Property
DateLastAccessed Property
DateLastModified Property
Drive Property
Files Property
IsRootFolder Property
Name Property
ParentFolder Property
Path Property
ShortName Property
ShortPath Property
SubFolders Property
Type Property
Microsoft® Visual Basic® Scripting Edition Size Scripting Run-Time Reference
Property
Applies To
File Object
Folder Object
Microsoft® Visual Basic® Scripting Edition Skip Scripting Run-Time Reference
Method
See Also
Close Method
Read Method
ReadAll Method
ReadLine Method
SkipLine Method
Write Method
WriteLine Method
WriteBlankLines Method
Microsoft® Visual Basic® Scripting Edition Skip Scripting Run-Time Reference
Method
Applies To
TextStream Object
Microsoft® Visual Basic® Scripting Edition
See Also
Close Method
Read Method
ReadAll Method
ReadLine Method
Skip Method
Write Method
WriteLine Method
WriteBlankLines Method
Microsoft® Visual Basic® Scripting Edition
Applies To
TextStream Object
Microsoft® Visual Basic® Scripting Edition
See Also
Dictionary Object
FileSystemObject Object
Microsoft® Visual Basic® Scripting Edition
Properties
AtEndOfLine Property
AtEndOfStream Property
Column Property
Line Property
Microsoft® Visual Basic® Scripting Edition
Methods
Close Method
Read Method
ReadAll Method
ReadLine Method
Skip Method
SkipLine Method
Write Method
WriteLine Method
WriteBlankLines Method
Microsoft® Visual Basic® Scripting Edition
See Also
Attributes Property
DateCreated Property
DateLastAccessed Property
DateLastModified Property
Drive Property
Files Property
IsRootFolder Property
Name Property
ParentFolder Property
Path Property
ShortName Property
ShortPath Property
Size Property
SubFolders Property
Microsoft® Visual Basic® Scripting Edition Type Scripting Run-Time Reference
Property
Applies To
File Object
Folder Object
Microsoft® Visual Basic® Scripting Edition
See Also
Close Method
Read Method
ReadAll Method
ReadLine Method
Skip Method
SkipLine Method
Write Method
WriteBlankLines Method
Microsoft® Visual Basic® Scripting Edition
Applies To
TextStream Object
Microsoft® Visual Basic® Scripting Edition
See Also
InStr Function
Microsoft® Visual Basic® Scripting Edition
Arithmetic Operators
Assignment Operator
Comparison Operators
Concatenation Operators
Logical Operators
Description
The following nonintrinsic math functions can be derived from the intrinsic
math functions:
Messages
Error
Message
Code
5 Invalid procedure call or argument
6 Overflow
7 Out of memory
9 Subscript out of range
10 Array fixed or temporarily locked
11 Division by zero
13 Type mismatch
14 Out of string space
28 Out of stack space
35 Sub or Function not defined
48 Error in loading DLL
51 Internal error
53 File not found
57 Device I/O error
58 File already exists
61 Disk full
67 Too many files
70 Permission denied
75 Path/File access error
76 Path not found
91 Object variable or With block variable not set
92 For loop not initialized
94 Invalid use of Null
322 Can't create necessary temporary file
424 Object required
429 ActiveX component can't create object
430 Class doesn't support Automation
File name or class name not found during Automation
432
operation
438 Object doesn't support this property or method
440 Automation error
445 Object doesn't support this action
446 Object doesn't support named arguments
447 Object doesn't support current locale setting
448 Named argument not found
449 Argument not optional
Wrong number of arguments or invalid property
450
assignment
451 Object not a collection
453 Specified DLL function not found
455 Code resource lock error
This key already associated with an element of this
457
collection
Variable uses an Automation type not supported in
458
VBScript
500 Variable is undefined
501 Illegal assignment
502 Object not safe for scripting
503 Object not safe for initializing
1001 Out of memory
1002 Syntax error
1003 Expected ':'
1004 Expected ';'
1005 Expected '('
1006 Expected ')'
1007 Expected ']'
1008 Expected '{'
1009 Expected '}'
1010 Expected identifier
1011 Expected '='
1012 Expected 'If'
1013 Expected 'To'
1014 Expected 'End'
1015 Expected 'Function'
1016 Expected 'Sub'
1017 Expected 'Then'
1018 Expected 'Wend'
1019 Expected 'Loop'
1020 Expected 'Next'
1021 Expected 'Case'
1022 Expected 'Select'
1023 Expected expression
1024 Expected statement
1025 Expected end of statement
1026 Expected integer constant
1027 Expected 'While' or 'Until'
1028 Expected 'While', 'Until', or end of statement
1029 Too many locals or arguments
1030 Identifier too long
1031 Invalid number
1032 Invalid character
1033 Unterminated string constant
1034 Unterminated comment
1035 Nested comment
1037 Invalid use of 'Me' keyword
1038 'Loop' without 'Do'
1039 Invalid 'Exit' statement
1040 Invalid 'For' loop control variable
1041 Name redefined
1042 Must be first statement on the line
1043 Can't assign to non-ByVal argument
1044 Can't use parens when calling a Sub
1045 Expected literal constant
1046 Expected 'In'
32766 True
32767 False
32811 Element not found
Microsoft® Visual Basic® Scripting Edition
Description
Syntax
Part Description
Required. The numeric designation for the day of
weekday the week. Numeric value of each day depends on
setting of the firstdayofweek setting.
Optional. Boolean value that indicates if the
weekday name is to be abbreviated. If omitted,
abbreviate
the default is False, which means that the
weekday name is not abbreviated.
Optional. Numeric value indicating the first day
firstdayofweek
of the week. See Settings section for values.
Settings
Remarks
Dim MyDate
MyDate = WeekDayName(6, True) ' MyDate contains Fri.
Microsoft® Visual Basic® Scripting Edition