VBScript Objects

In this chapter, you will examine how VBScript interacts with its environment by working with objects. This will include an examination of VBScript's built-in and run-time objects as well as a complete listing of the objects' associated properties and methods. In addition, you'll get a brief overview of the importance of browser- and WSH-specific objects. You will also learn how to create your own custom objects replete with their own sets of properties and methods.

VBScript Object Based Programming

In order to get any real work done, VBScript depends upon the use of objects. An object provides access to system resources and data manipulation structures by way of methods and properties. Methods are functions built into objects that, when executed, interact with or manipulate the resources represented by the objects. Properties are qualities of the resources represented by objects that describe the resource in some manner. Some properties are read-only, allowing VBScript to collect information about the resource. Other properties can be modified, thus providing the ability to directly change some quality of a resource represented by an object.

By itself, VBScript has only limited capabilities. It cannot access HTML page elements, the Windows file system, or other system resources. VBScript supplies only a small collection of built-in objects. These objects provide VBScript with the ability to react to errors and to parse and extract data from strings. VBScript's built-in objects are listed in Table 7.1.

Table 7.1: VBScript Built-in Objects

Object

Description

Class

Provides the ability to create custom objects

Properties: This object does not support any properties

Methods: This object does not support any methods

Events: Initialize, Terminate

Err

Provides details about run-time errors

Properties: Description, HelpContext, HelpFile, Number, Source

Methods: Clear, Raise

Events: This object does not support any events

Match

Accesses read-only properties of a regular expression match

Properties: FirstIndex, Length, Value

Methods: This object does not support any methods

Events: This object does not support any events

Matches Collection

A collection of regular expression Match objects

Properties: This object does not support any properties

Methods: This object does not support any methods

Events: This object does not support any events

RegExp

Supports regular expressions

Properties: Global, IgnoreCase, Pattern

Methods: Execute, Replace, Test

Events: This object does not support any events

SubMatches Collection

Accesses read-only values of regular expression submatch strings

Properties: This object does not support any properties

Methods: This object does not support any methods

Events: This object does not support any events

  Note

VBScript's built-in collection of objects is provided by the VBScript interpreter. These objects are available to all VBScripts regardless of the environment in which they are executed.

Properties Belonging to VBScript s Built in Objects

As Table 7.1 indicates, VBScript's built-in collection of objects provides access to a number of different properties. Table 7.2 lists each of these properties and describes their purpose.

Table 7.2: VBScript Object Properties

Property

Description

Description

Retrieves an error message

FirstIndex

Returns the first position of a specified substring in a string

Global

Changes or retrieves a Boolean value

HelpContext

Retrieves the context ID of a Help file topic

HelpFile

Returns the path to a Help file

IgnoreCase

Retrieves a Boolean value that indicates whether a pattern search is case-sensitive

Length

Returns the length of a search string match

Number

Returns the error number for the specified error

Pattern

Retrieves the regular expression pattern in a search operation

Source

Retrieves the name of the object that generates an error

Value

Returns the value of a search string match

Methods Belonging to VBScript s Built in Objects

VBScript's built-in Err and RegExp objects provide access to a small number of methods. Table 7.3 lists each of these methods and describes their purpose.

Table 7.3: VBScript Object Methods

Object

Method

Description

Err

Clear

Clears an Err object's property settings

Err

Raise

Used to simulate a run-time error

RegExp

Execute

Performs a regular expression search against a string

RegExp

Replace

Replaces text in a regular expression search

RegExp

Test

Performs a regular expression search against a string


Working with VBScript s Built in Objects

As Table 7.1 shows, VBScript provides a number of built-in objects. These objects provide the ability to perform all of the following actions:

  • Work with VBScript run-time errors
  • Define custom objects and assign to them properties and methods
  • Perform character and pattern matching using regular expressions

The next several sections cover some of these objects and their capabilities.

The Err Object

You already learned how to work with the built-in Err object back in Chapter 6, "Data Collection, Notification, and Error Reporting." This object provides access to run-time error information by providing access to the following properties:

  • Description. A string describing the error condition
  • Error Number. The VBScript error number associated with the error
  • Source. The name of the resource that reported the error
  • HelpContext. Sets a context ID for a topic in the specified Help file
  • HelpFile. The name and location of an external file containing help information

In addition, this object provides two methods for working with errors:

  • Clear(). Deletes information stored by the Err object regarding the current error
  • Raise(). Provides the ability to generate and test run-time errors

The Class Object

VBScript provides support for a number of different data subtypes, including strings and dates. VBScript also supports the more complex array data structure. VBScript provides the Class object as a means of creating a customized complex data structure, or custom objects. By creating your own custom objects, you can encapsulate data functions to create new objects, which your VBScripts can then access like any other objects. Creating custom objects provides your scripts with a tool that helps ensure data consistency, because it allows you to define procedures for validating and enforcing object properties and for controlling object manipulation.

Class Object Syntax

Custom objects are created using the Class…End Class statement. The Class object therefore provides a template for defining other objects and their structures. Once defined, these objects can be instantiated just like another object. The syntax for this statement is outlined below.

Class ClassName
 Statements
End Class

ClassName represents the name to be assigned to the new object. Statements represent the variables, properties, and methods defined within the object. Methods are established by defining the Sub or Function procedures. Properties are defined by using any of the following statements to manipulate variables defined within the Class…End Class statement:

  • Property Get. Provides the ability to retrieve the value assigned to a private variable
  • Property Let. Provides the ability to change the value assigned to a private variable
  • Property Set. Provides the ability to change the value of an object variable

Creating Variables, Properties, and Methods

Variables, properties, and methods can be defined as public (accessible throughout the script) or private (available only within the Class) using the Public and Private keywords. Unless specified, Public is always assumed.

  Note

Although you can allow variables defined within the Class…End Class statement to have a public scope, this is not recommended. This prevents you from being able to validate the value assigned to the variable from within the object. Instead, it is recommended that you make all variables private and expose them using the Property Get and Property Let statements. This way, you can build data-validation logic into your object and ensure data integrity.

The following example demonstrates how to use the Class object to create a custom object called Customer.

Class Customer

 Private strCustName

 Public Property Get CustomerName
 CustomerName = strCustName
 End Property

 Public Property Let CustomerName (strNameAssignment)
 StrCustName = strnameAssignment
 End property

 Function DisplayName
 MsgBox(strCustName)
 End Function
End Class

The first statement defines a private variable named strCustName. The next three statements use that variable to create a property and make it readable. The three statements that follow make the property writable. Finally, the last three statements within the Class…End Class statement define a function that will serve as an object method.

Now that a new object has been defined, you can instantiate it, as shown below.

Dim objCustName
Set objCustName = New Customer

You can then store a customer's name to the object.

objCustName.CustomerName = "ABC Inc."

You can then execute the object's DisplayGreeting() method.

objCustName.DisplayName()
  Note

Data stored in objects is destroyed as soon as the script ends. This has a somewhat limiting effect on its value. However, there are a number of ways to store and retrieve object data. For example, when working with the WSH, you could write object data to a file or store it in a system variable. Similarly, when using VBScript in Web page development, you could store nonsensitive object data locally on client computers using cookies.

Setting Up Initialization and Termination Procedures

Objects created by the Class…End Class statement support the following events:

  • Class_Initialize. If present, this method executes whenever an instance of the object is created, providing an opportunity to perform initialization tasks such as defining initial variable values.
  • Class_Terminate. If present, this method executes whenever an instance of the object is destroyed, providing an opportunity to perform any required cleanup tasks.

The following statements demonstrate how to trigger statement execution based on the occurrence of the Class_Initialize and Class_Terminate events.

Private Sub Class_Initialize
 MsgBox("The Class_Initialize Subroutine is executing!")
End Sub

Private Sub Class_Terminate
 MsgBox("The Class_Terminate Subroutine is executing!")
End Sub

Once added inside a Class…End Class statement, these events will automatically execute whenever a new instance of the associated object is created or destroyed.

  Note

You can create a new instance of a custom object using the Set statement and the New keywords, as demonstrated below.

 Set objCustName = New Customer

Similarly, you can destroy a custom object using the Set statement.

 Set objCustName = Nothing

Nothing is a VBScript keyword that disassociates an object variable from an object. As long as no other object variables refer to the object in question, the memory used to store its data is released.

The RegExp Object and Other Related Objects

Except for the Err object and the Class object, all the rest of VBScript's built-in objects are designed to work with regular expressions. A regular expression is a pattern of text made up of characters and metacharacters. Regular expressions provide the ability to identify patterns and perform complex search and replace operations.

The RegExp object allows you to work with regular expressions in VBScript. To add a RegExp object to your VBScripts, you must first define a variable to represent it and then use the New keyword to instantiate it, as demonstrated below.

Dim regExpObj
Set regExpObj = New RexExp

The RegExp object has three properties:

  • Pattern. Specifies the regular expression pattern to be matched
  • IgnoreCase. A Boolean value that determines whether a case-sensitive search is performed
  • Global. A Boolean value that determines whether all occurrences of a pattern match should be replaced

In addition, the RegExp object provides a number of methods, one of which is the Replace() method. This method replaces the matching text patterns in a search string. Its syntax is shown in the following statement.

RegExp.Replace(String1, String2)

String1 is the string in which the replacements are to occur and String2 is the replacement string.

For example, the following statements demonstrate how to use the RegExp object to search a string variable called strQuote and replace an occurrence of the word child.

Dim regExpObj, strQuote
Set regExpObj = New RegExp
regExpObj.Pattern = "boy"
strQuote = "Once upon a time there was a little boy."
MsgBox RegExpObj.Replace(strQuote, "child")

The first two statements in this example define and create an instance of the RegExp object named regExpObj. The next line uses the RegExp project's Pattern property to set a search pattern. The statement that follows sets up the string to be searched. Finally, the last statement in the example replaces the first occurrence of the characters boy with the characters child (the value assigned to the RegExp Pattern property).

The previous example replaces only the first occurrence of the specified pattern match. However, you can modify the search pattern as shown below to search for and replace all pattern matches in the search string.

Dim regExpObj, strQuote
Set regExpObj = New RegExp
regExpObj.Pattern = "boy"
regExpObj.Global = True
strQuote = "Once upon a time there was a little boy."
MsgBox RegExpObj.Replace(strQuote, "child")

As you can see, a new statement has been added to the example, which uses the Global property of the RegExp property to replace all matching instances in the search string. VBScript also supplies a number of metacharacters that you can use when working with the RegExp object's Pattern property. For example, the following statements perform a pattern replacement using a range of values:

Dim regExpObj, strQuote
Set regExpObj = New RegExp
regExpObj.Pattern = "[d]"
regExpObj.Global = True
strQuote = "Your customer number is 8."
MsgBox RegExpObj.Replace(strQuote, "1008")

The d metacharacter specifies that any single digit should be used as the replacement string. In the case of this example, the number 8 is replaced with the number 1008. Table 7.4 lists the metacharacters supported by VBScript regular expressions.

Table 7.4: VBScript Object Methods

Character

Description

Sets the next character as a special character, a back reference, a literal, or an octal escape

Matches the beginning of the input string

$

Matches the end of the input string

*

Matches the preceding expression (zero or more times)

+

Matches the preceding expression (one or more times)

?

Matches the preceding expression (zero or one time)

{n}

Matches exactly n times

{n,}

Matches a minimum of n times

{n, m}

Matches a minimum of n times and a maximum of m times

.

Matches any individual character except the newline character

(pattern)

Matches a pattern and allows the matched substring to be retrieved from the Matches collection.

x|y

Matches x or y

[xyz]

Matches any of the specified characters

[⁁xyz]

Matches any character except those specified

[a-z]

Matches any character specified in the range

[⁁a-z]

Matches any character except for those specified in the range



Matches on a word boundary

B

Matches on a non-word boundary

cx

Matches the control character specified as x

d

Matches a single digit number

D

Matches any single non-numeric character

f

Matches the form-feed character

Matches the newline character

Matches the carriage return character

s

Matches any white space character (for example, space, tab, form-feed)

S

Matches any non-white-space character

Matches the tab character

v

Matches the vertical tab character

w

Matches any word character

W

Matches any non-word character

xn

Matches n, where n is a two-digit hexadecimal escape value

num

Matches num, where num is a positive integer in a backward reference to captured matches

Specifies an octal escape value or a back reference

nml

Matches octal escape value nml where n is an octal digit in the range of 0–3 and m and l are octal digits in the range of 0–7

un

Matches n, where n is a four-digit hexadecimal Unicode character

The RegExp object provides two additional methods, as outlined below.

  • Test(). Searches a regular expression and returns a Boolean value indicating whether a matching pattern was found
  • Execute(). Creates a Matches collection from a search of a regular expression

The Test() Method

The Test() method allows you to check whether a string contains a pattern match. It has the following syntax:

RegExp. Test(string)

For example, the following statements demonstrate how to use the Text() method to report on the presence or absence of a pattern match:

Dim regExpObj, strQuote
Set regExpObj = New RegExp
regExpObj.Pattern = "boy"
strQuote = "Once upon a time there was a little boy."
If regExpObj. Test(strQuote) = True Then
 MsgBox "Match Found"
Else
 MsgBox "No Match Found"
End If

The Execute() Method

The RegExp object's Execute() method creates a Matches collection from a search of a regular expression and has the following syntax:

RegExp.Execute(string)

The resulting Matches collection is read-only, as are the individual Match objects that make up the collection. Once created, you can loop through each object in the Matches collection and process it, as demonstrated in the following example.

'*************************************************************************
'Script Name: Script 7.1.vbs
'Author: Jerry Ford
'Created: 02/05/2003
'Description: Performing Regular Expression pattern replacements
'*************************************************************************

'Initialization Section

Option Explicit

Dim regExpObj, strQuote, colMatchStmts, strDisplayText, intCount, Match
Set regExpObj = New RegExp

regExpObj.Pattern = "File" 'Specify the string to search for

regExpObj.Global = True 'Perform a global pattern match

'Specify the string to be searched
strQuote = "Filename filename logFile logfile File file"


'Main Processing Section

CreateMatchesCollection()
ProcessMatchesConnection()
DisplayResults()


'Procedure Section

Sub CreateMatchesCollection()
 'Use the RegExp object's Execute() method to create a matches collection
 Set colMatchStmts = regExpObj.Execute(strQuote)
End Sub

Sub ProcessMatchesConnection()
 'Set up a counter to count the number of matches found
 intCount = 0
 'Loop through the Matches collection
 For Each Match in colMatchStmts
 'Build a string that displays the location where each match was found
 strDisplayText = strDisplayText & "A match occurred at position " & _
 Match.FirstIndex & vbCrLf
 intCount = intCount + 1
 Next
End Sub

Sub DisplayResults()
 'Display the results
 MsgBox "Total number of matches = " & intCount & vbCrLf & vbCrLf & "" & _
 strDisplayText
End Sub

In this example, a Matches collection consisting of three Match objects is created using the RegExp object's Execute() method. Each of these match objects has its own set of associated properties, including the FirstIndex property, which specifies the location in the search string where a match is found. A For Each…Next loop is then used to assemble a display string that shows the location of each pattern match, as shown in Figure 7.1.

click to expand
Figure 7.1: Processing the contents of a Matches collection created by the RegExp object's Execute() method


Other Collections of Objects Available to VBScript

VBScript's limited built-in collection of objects makes it a safe scripting language, meaning that it has no inherent ability to affect the environment in which it operates. In order to operate in and control the environment in which it executes, VBScript depends on external collections of objects.

Browser Based Objects

VBScripts that are executed within HTML pages and loaded into Internet Explorer have access to two different collections of objects. The first collection of objects is referred to as the DHTML (Dynamic HTML) object model. This is an older object model originally developed for Internet Explorer versions 3 and 4. The DHTML object model is also supported by Internet Explorer 5 and 6 for the purposes of backward compatibility. The second collection of objects is known as the DOM (Document Object Model). This object model provides VBScript with the ability to access and control objects on an HTML page, such as links, images, frames, forms, and form elements.

  Note

For more information on the object models provided by Internet Explorer, refer to Chapter 8, "VBScript and Internet Explorer."

Objects Available When Executed in the WSH

When VBScripts are executed by the WSH, they have access to two different sets of objects. One set of objects available to VBScripts executed by the WSH is referred to as the WSH core object model. The objects that make up this object model provide access to a collection of Windows resources, including the Windows desktop, file system, registry, and network resources.

  Note

For more information on the WSH object model, refer to Chapter 9, "VBScript and the WSH."

The second set of objects is referred to as VBScript run-time objects. These objects are provided by an external DLL (Dynamic Link Library) named scrrun.dll. They provide VBScript with the ability to access the Windows file system. In addition, the VBScript run-time objects include an object known as a Dictionary object. The Dictionary object allows you to store data in an associative array and to retrieve the data stored in that array using keys instead of an index position as is the case with regular VBScript arrays. VBScript's run-time objects are listed in Table 7.5.

Table 7.5: VBScript Run-Time Objects

Object Name

Description

Dictionary

Stores data key, item pairs

Properties: Count, Item, Key

Methods: Add, Exists, Items, Keys, Remove, RemoveAll

Drive

Provides script with access to disk properties

Properties: AvailableSpace, DriveLetter, DriveType, FileSystem, FreeSpace, IsReady, Path, RootFolder, SerialNumber, ShareName, TotalSize, VolumeName

Methods: This object does not support any methods

Drives Collection

Provides script with access to information regarding a drive's location

Properties: Count, Item

Methods: This object does not support any methods

File

Provides script with access to file properties

Properties: Attributes, DateCreated, DateLastAccessed, DateLastModified, Drive, Name, ParentFolder, Path, ShortName, ShortPath, Size, Type

Methods: Copy, Delete, Move, OpenAsTextStream

Files Collection

Provides scripts with access to files stored in a specified folder

Properties: Count, Item

Methods: This object does not support any methods

FileSystemObject

Provides scripts with access to the file system

Properties: Drives

Methods: BuildPath, CopyFile, CopyFolder, CreateFolder, CreateTextFile, DeleteFile, DeleteFolder, DriveExists, FileExists, FolderExists, GetAbsolutePathName, GetBaseName, GetDrive, GetDriveName, GetExtensionName, GetFile, GetFileName, GetFolder, GetParentFolderName, GetSpecialFolder, GetTempName, MoveFile, MoveFolder, OpenTextFile

Folder

Provides scripts with access to folder properties

Properties: Attributes, DateCreated, DateLastAccessed, DateLastModified, Drive, Files, IsRootFolder, Name, ParentFolder, Path, ShortName, ShortPath, Size, SubFolders, Type

Methods: Copy, Delete, Move, OpenAsTextStream

Folders Collection

Provides scripts with access to folders located within another folder

Properties: Count, Item

Methods: Add

Properties Belonging to VBScript Run-Time Objects

VBScript run-time objects provided by the WSH offer an extensive collection of properties. These properties provide information about the Windows file system and Windows files and folders. Table 7.6 contains a complete list of run-time properties.

Table 7.6: VBScript Run-Time Properties

Property Name

Description

AtEndOfLine

Returns a value of either True or False based on whether the file pointer has reached the TextStream file's end-of-line marker

AtEndOfStream

Returns a value of either True or False based on whether the end of a TextStream file has been reached

Attributes

Modifies or retrieves file and folder attributes

AvailableSpace

Retrieves the amount of free space available on the specified drive

Column

Retrieves the current column position in a TextStream file

CompareMode

Sets or returns the comparison mode used to compare a Dictionary object's string keys

Count

Returns a value representing the number of items in a collection or Dictionary object

DateCreated

Retrieves a file or folder's creation date and time

DateLastAccessed

Retrieves the date and time that a file or folder was last accessed

DateLastModified

Retrieves the date and time that a file or folder was last modified

Drive

Retrieves the drive letter where a file or folder is stored

DriveLetter

Retrieves the specified drive's drive letter

Drives

Establishes a Drives collection representing all the drives found on the computer

DriveType

Returns a value identifying a drive's type

Files

Establishes a Files collection to represent all of the File objects located within a specified folder

FileSystem

Retrieves the name of the file system used on the specified drive

FreeSpace

Retrieves the amount of free space available on the specified drive

IsReady

Returns a value of either True or False based on the availability of the specified drive

IsRootFolder

Returns a value of either True or False based on whether the specified folder is the root folder

Item

Retrieves or sets an item based on the specified Dictionary object key

Key

Sets a Dictionary object key

Line

Retrieves the current line number in the TextStream file

Name

Gets or modifies a file or folder's name

ParentFolder

Returns a reference the specified file or folder's parent folder object

Path

Retrieves the path associated with the specified file, folder, or drive

RootFolder

Retrieves the Folder object associated with the root folder on the specified drive

SerialNumber

Retrieves the specified disk volume's serial number

ShareName

Retrieves the specified network drive's share name

ShortName

Retrieves the specified file or folder's 8.3 character short name

ShortPath

Retrieves a file or folder's short path name associated with a file or folder's 8.3 character name

Size

Returns the number of bytes that make up a file or folder

SubFolders

Establishes a Folders collection made up of the folders located within a specified folder

TotalSize

Retrieves a value representing the total number of bytes available on a drive

Type

Retrieves information about the specified file's or folder's type

VolumeName

Gets or modifies a drive's volume name

Methods Belonging to VBScript Run-Time Objects

VBScript's run-time methods provide the ability to access the Windows file system; to create, modify, and delete files and folders; and to create and process text files. Table 7.7 contains a complete list of the methods provided by VBScript's run-time objects.

Table 7.7: VBScript Run-Time Methods

Method Name

Description

Add (Dictionary)

Adds a key and item pair to a Dictionary object

Add (Folders)

Adds a Folder to a collection

BuildPath

Appends a name to the path

Close

Closes an open TextStream file

Copy

Copies a file or folder

CopyFile

Copies one or more files

CopyFolder

Recursively copies a folder

CreateFolder

Creates a new folder

CreateTextFile

Creates a file and a TextStream object so that it can be read from and written to

Delete

Deletes a file or folder

DeleteFile

Deletes a file

DeleteFolder

Deletes a folder's contents

DriveExists

Returns a value of True or False based on whether a drive exists

Exists

Returns a value of True or False based on whether a key exists in a Dictionary object

FileExists

Returns a value of True or False based on whether the specified file can be found

FolderExists

Returns a value of True or False based on whether the specified folder can be found

GetAbsolutePathName

Retrieves a complete path name

GetBaseName

Retrieves a file name without its file extension

GetDrive

Returns the Drive object associated with the drive in the specified path

GetDriveName

Returns the name of a drive

GetExtensionName

Returns a file's extension

GetFile

Returns a File object

GetFileName

Returns the last file name or folder of the specified path

GetFileVersion

Returns a file's version number

GetFolder

Returns the Folder object associated with the folder in the specified path

GetParentFolderName

Returns the name of the parent folder

GetSpecialFolder

Returns a special folder's name

GetTempName

Returns the name of a temporary file or folder

Items

Returns an array where items in a Dictionary object are stored

Keys

Returns an array containing the keys in a Dictionary object

Move

Moves a file or folder

MoveFile

Moves one or more files

MoveFolder

Moves one or more folders

OpenAsTextStream

Opens a file and retrieves a TextStream object in order to provide a reference to the file

OpenTextFile

Opens a file and retrieves a TextStream object in order to provide a reference to the file

Read

Returns a string containing a specified number of characters from a TextStream file

ReadAll

Reads the entire TextStream file and its contents

ReadLine

Reads an entire line from the TextStream file

Remove

Deletes a Dictionary object's key, item pair

RemoveAll

Deletes all Dictionary objects' key, item pairs

Skip

Skips a specified number of character positions when processing a TextStream file

SkipLine

Skips an entire line when processing a TextStream file

Write

Places a specified string in the TextStream file

WriteBlankLines

Writes a specified number of newline characters to the TextStream file

WriteLine

Writes the specified string to the TextStream file

The Run-Time Dictionary Object

All of the VBScript run-time objects, except for the Dictionary object, are designed to work with files and the Windows file system. Use of these objects is covered extensively in Parts III, IV, and V of this book. This section provides a review of the Dictionary object.

The Dictionary object and the FileSystemObject object are the two top-level VBScript run-time objects. The Dictionary object provides the ability to set up an associative array based on key and item pairs. In other words, unlike traditional VBScript arrays, which store and retrieve data based on its indexed position within the array, items stored in a Dictionary object are stored and retrieved using a key. This key can be a number, a string, or any of the data subtypes supported by VBScript. The Dictionary object does not even support the use of index numbers because it does not store items based on order. The Dictionary object has all the benefits of an array while providing greater flexibility in storing and retrieving data. In addition, the Dictionary object provides a number of properties and methods that enhance your ability to control data stored in a Dictionary object.

The Dictionary object supports three properties:

  • Count. Retrieves the number of items stored in a Dictionary object
  • Item. Retrieves or adds an item with a specified key in a Dictionary object
  • Key. Adds a key in a Dictionary object

In addition, the Dictionary object provides access to the following methods:

  • Add. Adds a key and item pair to a Dictionary object
  • Exists. Returns a Boolean value of True if a specified key exists in the Dictionary object and False if it does not
  • Items. Returns an array containing all the items in a Dictionary object
  • Keys. Returns an array containing all existing keys in a Dictionary object
  • Remove. Removes a key, item pair from a Dictionary object
  • RemoveAll. Removes all key, item pairs from a Dictionary object

To better demonstrate the implementation of the Dictionary object, consider the following example. To add an instance of the Dictionary object to a VBScript, you must first define a variable by which it can be referenced and then create an instance of the object.

Dim dicObject
Set dicObject = CreateObject("Scripting.Dictionary")

Once instantiated, you may then store items in the object along with their associated keys, as demonstrated below.

dicObject.Add "Aug2003Rpt", "AugReports.txt"
dicObject.Add "Sep2003Rpt", "SepReports.txt"
dicObject.Item("Oct2003Rpt") = "OctReports.txt"

The first two statements add data to the Dictionary object using the Add() method. The first argument specified is the key that is to be associated with the data, which follows as the second argument. The last statement adds a third piece of data by using the Item() property, thus demonstrating that if you reference a key/item pair that does not exist, VBScript will automatically add it for you.

Once you have populated your Dictionary object with data, you can come back and work with its data. For example, the following statements use the Exists() method to determine whether a key/item pair exists. If it does, then the Item() method retrieves and displays a data element by supplying its associated key.

If dicObject.Exists("Sep2003Rpt") = True Then
 MsgBox "The value stored in Sep2003Rpt is " & dicObject.Item("Sep2003Rpt")
End If

Removing key/item pairs from a Dictionary object is just as easy as adding them. For example, the following statement shows how to use the Remove() method to delete a data element using its associated key:

DicObject.Remove "Sep2003Rpt"

Alternatively, if you prefer to delete all the data stored in a Dictionary object, you may do so using the RemoveAll() method, as shown below.

DicObject.RemoveAll


Summary

In this chapter, you were presented with a complete listing of VBScript's built-in and run-time objects. In addition to reviewing these objects and their associated properties and methods, you learned how to create your own custom objects. You also learned how to create an associative array using the Dictionary object when developing VBScripts that run with the WSH. Other object models were also discussed, including those provided by Internet Explorer and the WSH.


Part I - Introducing Microsoft VBScriptBasics

Part II - Professional Project 1 Desktop Administration Using VBScript and the WSH

Part III - Professional Project 2 Analyzing Application Logs

Part IV - Professional Project 3 Creating a Centralized Report Management Station

Part V - Professional Project 4 Reporting Application Summary Data via the Web

Part VI - Introducing Microsoft VBScriptBasics



Microsoft VBScript Professional Projects
Microsoft VBScript Professional Projects
ISBN: 1592000568
EAN: 2147483647
Year: 2005
Pages: 366

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net