An Introduction to the Scripting Runtime Object Library

This content is no longer actively maintained. It is provided as is, for anyone who may still be using these technologies, with no warranties or claims of accuracy with regard to the most recent product version or service release.

An Introduction to the Scripting Runtime Object Library

by Susan Sales Harkins

Application: Microsoft Access 2000
Operating System: Microsoft Windows

Although some applications link to foreign files, an Access database generally contains all the objects an application needs. As a result, file management isn't the same kind of laborious affair it is with other applications. However, that doesn't mean you'll never need to work with data files and folders. If you're lucky, the task will be small and easily handled by the VBA functions and statements. On the other hand, major file management can quickly run into some long, convoluted code. When this is the case, we recommend you consider using the Scripting Runtime Object Library instead of the VBA functions and statements. You'll find this library much better suited to file management than VBA's counterparts. Although the Scripting Runtime Object Library was born from the need to manipulate files via the Internet, you'll find it works equally well with most Visual Basic applications.

The details

Microsoft Office 2000 installs the Microsoft Scripting Runtime Object Library (scrrun.dll). Once you have the DLL, all you should have to do is reference it via the Visual Basic Editor (VBE) to gain access to its objects. To do so, while in the VBE choose References from the Tools menu. Then, you simply check the Microsoft Scripting Runtime option and click OK. Once you reference the library, you have access to the objects listed in Table A. Figure A shows a diagram of the object model hierarchy.

Table A: Scripting Runtime objects

Object Description
Dictionary The Dictionary object is king of the hill; it's the object at the very top of the hierarchy.
FileSystemObject Another top-level object, FileSystemObject accesses drives, folders and files.
Drive The Drive object belongs to the Drives collection and refers to a particular local or network drive.
Folder This object refers to a specific folder.
File The Files collection contains File objects, each of which refers to a file.
TextStream This object refers to a stream of text that can be read from, written to or appended to a text file.

Figure A: The Dictionary object is the top level of the Scripting Runtime model.

About the Dictionary object

At the top of the heap, the Dictionary object is a data structure that contains what could be described as an index. Dictionary objects store pairs of data. One half of the pair is an item of any data type. The second half is a key that consists of a unique string that identifies the item. In a way, this structure is similar to a VBA collection, with a few more bells and whistles. The primary purpose of a Dictionary object is to create a collection of related files, which you can then search or otherwise manipulate.

Declaring the Dictionary object
The Dictionary and FileSystemObject objects are the top levels of the scripting model. To declare and define a Dictionary object, use the Dictionary type in the form

Dim dct As Scripting.Dictionary
Set dct = New ScriptingDictionary

Or, you can sometimes use the statement

Dim dct As New Scripting.Dictionary

These two statements create an object variable named dct of the Dictionary type and then set a new instance of a Dictionary object.

About the FileSystemObject object

The FileSystemObject object is the object that actually gives you access to a system's files using 27 methods and only one property. We won't try to define all of the methods, but we'll review a few as we use them in code examples a little later. In addition, FileSystemObject is used to return an object that can create, read and edit text files (ASCII and Unicode).

Declaring the FileSystemObject object
Similar to the Dictionary object, FileSystemObject requires a variable of the FileSystemObject type and a new instance of the FileSystemObject in the form

Dim fso As Scripting.FileSystemObject
Set fso = New Scripting.FileSystemObject

Or, as an alternative, you can use the statement

Dim fso As New Scripting.FileSystemObject

Once you have a new instance of the FileSystemObject, you can work with drives, folders and files, which provide easy access to the file system and simplify the process of reading and writing to a text file.

Some file management examples

Once you reach this point, you're ready to start working with the actual files by declaring the appropriate data type and then using the appropriate method or property to get the job done. Immediately beneath the FileSystemObject object in the Microsoft Scripting Runtime Object model is the Drives collection, containing Drive objects. There are a number of properties associated with Drive objects, which determine such items as the letter assigned to a drive, its size, available space, whether the drive is removable, fixed, networked or a CD-ROM, and whether it's available.

The Folder object, contained in the Folders collection, comes next in the object model and has 17 properties and four methods. Using this object, you can create, delete, move and copy folders. In addition, you can determine if a particular folder exists. This brings us to the File object, with a number of properties and methods that allow you to copy, delete, move and create files, as well as learn a file's size, name, path and type.

The CopyFolder method
Now that you know the major pieces that we'll be working with, let's look at the procedure in Listing A, which copies all the files in a folder to a new location. First, the procedure declares and sets an object variable as a FileSystemObject object. The second line uses the CopyFolder method to copy all the subfolders and files in the source folder to the destination folder. You can test the procedure in the Immediate window by entering the statement

?CopyFolder(source, destination)

where source is the name of the folder that contains the files you want to copy and destination is the name of the folder to which you want to copy those files. For instance, you might use

?CopyFolder("C:\My Documents", "C:\Made By Access")

If the destination folder doesn't exist, the CopyFolder method will create one. Specifying an invalid source folder returns an error, so we've added a simple error handler.

Listing A: CopyFolder() function

Function CopyFolder(source As String, _
    destination As String)
Dim fso As New Scripting.FileSystemObject
On Error GoTo errHandler
fso.CopyFolder source, destination
Set fso = Nothing
Exit Function

errHandler:
If Err = "76" Then MsgBox "Please enter a " & _
    "valid source folder", vbCritical
Set fso = Nothing
End Function

The VBA alternative would need to verify that the folder existed and then loop through all the files in that folder, copying each, one at a time.

The FileExists property
Another example uses the FileExists property to determine whether a file exists. The VBA alternative, while not terribly complex, does require more code because the Dir() function isn't as consistent as the FileExists property and there are more situations to consider. Listing B declares and defines the variable fso as a FileSystemObject. The second statement sets the function to True or False, depending on the results of the FileExists property. You can run this function from the Immediate window by entering the statement

?FileTest(filename)

where filename is the complete path to the file you're checking. Be sure that you include the file's extension when specifying the filename; otherwise the function will return a False result.

Listing B: FileTest() function

Function FileTest(filename As String) _
    As Boolean
Dim fso As New Scripting.FileSystemObject
FileTest = fso.FileExists(filename)
Set fso = Nothing
End Function

Working with the TextStream object

There's still an object we need to review, and that's the TextStream object, which actually controls any reading and writing to a file. Like the other objects, the TextStream object has a number of properties and methods. The procedure shown in Listing C uses the WriteLine, WriteBlankLines and Close methods to append records to an error log.

Listing C: LogErrors() function

Function LogErrors(objErr As ErrObject)
Dim fso As New FileSystemObject
Dim fil As file
Dim txs As TextStream
Dim lng As Long
Dim str As String
lng = objErr.Number
str = objErr.Description

Set fil = fso.GetFile( _
    "C:\My Documents\errorlog.txt")
Set txs = fil.OpenAsTextStream(ForAppending)
With txs
    .WriteLine lng
    .WriteLine str
    .WriteLine Now
    .WriteBlankLines 1
    .Close
End With
Set fso = Nothing
Set fil = Nothing
Set txs = Nothing
End Function

When an error is raised, you'll want to pass the error to LogErrors() via your error handling code. The first several statements declare and define a number of variables. Specifically, we assign the error's number and description to the variables lng and str, respectively. Then, we define the text file, errorlog.txt, in the My Documents folder. This file must already exist for our procedure to work. If you want the procedure to create a new file when the file doesn't exist, use the FileSystemObject's``CreateTextFile method. The next statement

Set txs = fil.OpenAsTextStream(ForAppending)

defines and opens the TextStream object. In this case, we used the ForAppending constant, which allows us to write to the end of the file. The other constants are ForReading and ForWriting. You can't write to a file opened with the ForReading constant. If you open an existing file with the ForWriting constant, you'll overwrite the current contents.

The With statement uses TextStream methods to write the error number, description and the current date to the text file. Then, the WriteBlankLines method adds a blank line to separate errors from one another. The last three statements return the object variables to Nothing.

The procedure in Listing D will simulate an actual error so you can see how the log writing procedure works. The first step is to create the error log text file. You can use any text editor. Just open a blank file and save it. Be sure to update the path in LogErrors() if you use a path and filename other than C:\My Documents\errorlog.txt. When you run ForceErr(), the Raise statement forces the error 15--application-defined or object-defined error. The final statement passes this error to LogErrors(). You can run ForceErr() by opening the module in which you stored the procedure, positioning the cursor in any statement in the procedure, and clicking the Run Sub/UserForm button on the Visual Basic Editor's Standard toolbar. After you run ForceErr(), open the errorlog.txt file and review the results.

Listing D: Procedure to raise error

Function ForceErr()
On Error Resume Next
Err.Raise 15
LogErrors Err
End Function

One word of caution: The procedure can't update an open file. However, the procedure will still write to the disk version of the file. That means you may end up with an open text file that doesn't contain the latest information and with a saved file on disk that does. If you do open the file, be careful not to save it when you close it, just in case. In addition, you may want to add a bit of code to make sure the file is closed before you run the procedure. We've purposely left out extraneous and error-handling code to keep the code as simple as possible.

Not the last word

Don't consider this short introduction a definitive resource on the runtime library. We've just given you a quick look at the objects and a few properties and methods. Once you see the library work, it's clear that it does a lot with just a little coaxing. Although this library won't completely eliminate VBA's file management functions and statements, most VBA file management procedures can be replaced with a more efficient runtime procedure.

Copyright © 2001 Element K Content LLC. All rights reserved. Reproduction in whole or in part in any form or medium without express written permission of Element K Content LLC is prohibited. Element K is a service mark of Element K LLC.