C H A P T E R 5 | Microsoft Office 97/Visual Basic Programmer's Guide |
Microsoft Outlook Objects |
Microsoft Outlook 97, the desktop information management program included in Microsoft Office 97, is fully programmable and can be automated to build useful group software and mailenabled applications. Although Outlook doesn't contain Visual Basic for Applications version 5.0, it does include a complete type library and Visual Basic Scripting Edition (VBScript). Using the Outlook type library and VBScript, you can write procedures that respond to specific events such as opening or replying to a mail message or clicking a control on a form and store those procedures in a custom form. Using the type library and Visual Basic in Microsoft Access, Microsoft Excel, Microsoft Word, or Microsoft PowerPoint, you can control an entire Outlook session by using Automation (formerly OLE Automation).
This chapter provides a general overview of the objects exposed by the Outlook type library, and then it focuses on techniques for handling Outlook folders and items programmatically. Finally, the chapter compares Automation and VBScript and discusses the restrictions and guidelines for using each one.
Note This
chapter doesn't discuss designing and distributing custom Outlook
solutions. For information about developing Outlook solutions,
see Building Microsoft Outlook 97 Applications by Peter Krebs,
available from Microsoft Press (ISBN 1-57231-5736-9).
How Do I Display Visual Basic Help for Outlook? Visual Basic Help for Outlook isn't installed during setup; instead, you must copy the files Vbaoutl.hlp and Vbaoutl.cnt from the ValuPack folder to the folder in which you've installed Outlook. For more information about installing and using Visual Basic Help for Outlook, see "Getting Help for Visual Basic in Microsoft Outlook" in Outlook Help. To see the table of contents and index for Visual Basic Help for Outlook, you must display the Script Editor window while an Outlook item is open in design mode. To design an Outlook item, open any item except a note, and then click Design Outlook Form on the Tools menu. In design mode, click View Code on the Form menu to display the Script Editor. In the Script Editor, click Microsoft Outlook Object Library Help on the Help menu. The Help Topics dialog box should appear, displaying the table contents and index for Visual Basic Help for Outlook.
|
In the Outlook object model, the Application object contains the NameSpace object, which contains MAPIFolder objects that represent all the available folders in a given data source (for example, a MAPI message store). The MAPIFolder objects contain objects that represent all the Outlook items in the data source, and each item contains some useful programmable objects for controlling that item. In addition, there's an Explorer object associated with each folder and an Inspector object associated with each item.
For a visual representation of the Outlook object model, see "Microsoft Outlook Objects" in Help.
The Application object is the root object of the object model; it gives you easy access to all the other objects in the model. It gives you direct access to new items you create by using CreateItem, without having to traverse the object model, and it gives you access to the objects that represent the Outlook interface (the Explorer and Inspector objects). The Application object is the only Outlook object you can return by using the CreateObject or GetObject function in another application.
The NameSpace object can represent any recognized data source, such as a MAPI message store. The object itself provides methods for logging in and out, returning objects directly by ID, returning default folders directly, and gaining access to data sources owned by other users.
Note MAPI message stores, which are returned by the expression GetNameSpace("MAPI"), are the only data sources currently supported by Microsoft Outlook.
Folders Collection and MAPIFolder Object
The Folders collection contains all the MAPIFolder objects in the specified message store (or other recognized data source) or in a folder in that message store. For more information about using the objects that represent Outlook folders, see "Working with Outlook Folders" later in this chapter.
The Items collection contains all the Outlook items in the specified folder. Items and controls on items are the only objects in Outlook that support programmable events. For information about using the objects that represent Outlook items (such as MailItem and AppointmentItem) and the objects contained in Outlook items (such as Attachments and Recipients), as well as the events they support, see the following section, "Working with Outlook Items and Events."
Explorer and Inspector Objects
The Explorer object represents the window in which the contents of a folder are displayed. The Inspector object represents the window in which an Outlook item is displayed.
For information about using the Explorer and Inspector objects, see "Using Automation and VBScript" later in this chapter.
Just as you can use Outlook to explore the contents of any folder in your message store, you can automate Outlook to add folders or items to folders or to move and copy items and folders among folders in your message store.
To return the Folders collection from a NameSpace object or another MAPIFolder object, use the Folders property. To return a single MAPIFolder object, use Folders(index), where index is the folder's name or index number.
Note Folder names are casesensitive.
The following Automation example returns the folder named "Urgent"
from the message store for Shannon Boyd. This example assumes
that Shannon Boyd is currently logged on in Outlook.
Set olMAPI = GetObject("","Outlook.Application").GetNameSpace("MAPI")
Set urgentFolder = olMAPI.Folders("Mailbox - Shannon Boyd").Folders("Urgent")
Certain folders within an Outlook message store support the default functionality of Outlook and are created the first time Outlook is run. Each folder contains Outlook items of the same type. The following table describes these default folders.
Default folder | Description |
Calendar | Default container for AppointmentItem objects. |
Contacts | Default container for ContactItem objects. |
Deleted Items | Storage area into which all item objects are moved when they're marked for deletion. The application has options to retain such items indefinitely, archive them after a userdefined period of time or purge them when the application is closed. |
Inbox | Default container for MailItem objects. |
Journal | Default container for JournalItem objects. |
Notes | Default container for NoteItem objects. |
Outbox | Storage area for items that are completed but not sent. |
Sent Mail | Storage area into which copies of user-generated MailItem objects are moved when they're sent. |
Tasks | Default container for TaskItem objects. |
You can quickly return a default folder by using the GetDefaultFolders
method with the appropriate OlDefaultFolders constant.
The following VBScript example returns the Inbox folder for the
user who's currently logged on to Outlook.
Set olMAPI = Application.GetNameSpace("MAPI")
Set curInbox= olMAPI.GetDefaultFolder(6)
One of the most useful features of Outlook is delegation, where
one user delegates access to another user for one or more of their
default folders. Most often, this will be a shared Calendar folder
through which members of a group will coordinate their individual
schedules with a joint schedule or even a master schedule for
the group as a whole. To return a MAPIFolder object that
represents a shared default folder for a specific user, use the
GetSharedDefaultFolder method. The following Automation
example returns Kim Buhler's shared Calendar folder.
Set olMAPI = GetObject("","Outlook.Application").GetNameSpace("MAPI")
Set myRecipient = olMAPI.CreateRecipient("Kim Buhler")
myRecipient.Resolve
If myRecipient.Resolved Then
Set schedKim = olMAPI.GetSharedDefaultFolder(myRecipient, _
olFolderCalendar)
End If
You can set folders in the Outlook message store to contain only certain types of objects. For example, you can have the Calendar folder contain only AppointmentItem objects and have the Contacts folder contain only ContactItem objects.
Note When items of a specific type are saved, they're saved directly into their corresponding default folder. For example, when the GetAssociatedAppointment method is applied to a MeetingRequestItem object in the Inbox folder, the AppointmentItem object that's returned will be saved to the default Calendar folder.
To add a folder to the Folders collection, use the Add
method. The Add method has an optional argument you can
use to specify the type of items that can be stored in that folder.
By default, a folder created inside another folder inherits the
parent folder's type. The following VBScript example adds a new
folder named "Caterers" to the current (default) Contacts
folder.
Set olMAPI = Application.GetNameSpace("MAPI")
Set myContacts = olMAPI.GetDefaultFolder(10)
Set caterers = myContacts.Folders.Add("Caterers")
If you've used the ActiveExplorer property to return the
Explorer object that represents the currently displayed
folder in an Outlook session, you can use the CurrentFolder
property to return the corresponding MAPIFolder object,
as shown in the following Automation example.
Set olApp = GetObject("","Outlook.Application")
Set currFldr = olApp.ActiveExplorer.CurrentFolder
To return an Explorer object associated with a given MAPIFolder object, use the GetExplorer method.
Outlook items are represented by the fundamental objects in the Outlook object model. These objects represent mail messages, appointments or meetings, meeting requests, tasks, task requests, contacts, journal entries, posts, mail delivery reports, remote mail items, and notes. The following table describes the objects that represent Outlook items.
Object | Description |
AppointmentItem | Represents an appointment in the Calendar folder. An AppointmentItem object can represent either a one-time or recurring meeting or appointment. An appointment becomes a meeting when the MeetingStatus property is set to olMeeting and one or more resources (either personnel, in the form of required or optional attendees, or physical resources, such as a conference room) are designated. These actions result in the creation of a MeetingRequestItem object. |
ContactItem | Represents a contact in a Contacts folder. A contact can represent any person with whom you have any personal or professional contact. |
JournalItem | Represents a journal entry in a Journal folder. A journal entry represents a record of all Outlook-moderated transactions for any given period of time. |
MailItem | Represents a mail message in the Inbox folder or another mail folder. The MailItem object is the default item object and, to some extent, the basic element of Outlook. In addition to the MailItem object, Outlook also has a parallel PostItem object that has all of the characteristics of the mail message, differing only in that it's posted (written directly to a folder) rather than sent (mailed to a recipient), and it has two subordinate objects RemoteItem and ReportItem objects that are subsets of the mail message used to handle remote mail items and mail transport system reports, respectively. |
MeetingRequestItem | Represents a change to the recipient's Calendar folder, initiated either by another party or as a result of a group action. Unlike with other Outlook objects, you cannot create a MeetingRequestItem object or find an existing one in the Items collection.
This object is created automatically when you set the MeetingStatus property of an AppointmentItem object to olMeeting and send it to one or more users.
To return the AppointmentItem object associated with a MeetingRequestItem object and work directly with the AppointmentItem object to respond to the request, use the GetAssociatedAppointment method. |
NoteItem | Represents a note (an annotation attached to a document) in a Notes folder. |
PostItem | Represents a post in a public folder that other users can browse. This object is similar to the MailItem object, differing only in that it's posted (saved) directly to the target public folder, not sent (mailed) to a recipient. You use the Post method, which is analogous to the Send method for the MailItem object, to save the post to the target public folder instead of mailing it. |
RemoteItem | Represents a remote item in the Inbox folder or another mail folder. This object is similar to the MailItem object, but it contains only the Subject, Received, Date, Time, Sender, and Size properties and the first 256 characters of the body of the message. You use it to give someone who's connecting in remote mode enough information to decide whether or not to download the corresponding mail message. |
ReportItem | Represents a mail-delivery report in the Inbox folder or another mail folder. This object is similar to the MailItem object, and it contains a report (usually the nondelivery report) or error message from the mail transport system. |
TaskItem | Represents a task (an assigned, delegated, or self-imposed task to be performed within a specified time frame) in a Tasks folder. Like appointments or meetings, tasks can be delegated. Tasks are delegated when you assign them to one or more delegates, using the Assign method. |
TaskRequestItem | Represents a change to the recipient's task list, initiated either by another party or as a result of a group assignment. Unlike with other Outlook objects, you cannot create a TaskRequestItem object or find an existing one in the Items collection. It's created automatically when you apply the Assign method to a TaskItem object to assign (delegate) the associated task to another user.
To return the TaskRequestItem object and work directly with the TaskItem object to respond to the request, use the GetAssociatedTask method. |
The Items collection of a MAPIFolder object contains the objects that represent all the Outlook items in the specified folder. If a given folder doesn't contain any Outlook items, the Count property for the Items collection is 0 (zero).
To return the Items collection of a MAPIFolder object, use the Items property. To return a single AppointmentItem, ContactItem, JournalItem, MailItem, NoteItem, PostItem, or TaskItem object from its respective Items collection, use Items(index), where index is the item's name or index number.
The following example returns the first item with the subject
"Need your advice" in myFolder.
Set myItem = myFolder.Items("Need your advice")
The following example returns the first item in myFolder.
Set myItem = myFolder.Items(1)
To add items to the Items collection, use the Add method.
Note If you don't specify item type, it defaults to the type of the parent folder, or to MailItem if this folder doesn't have a type assigned to it. You can also assign to an item any valid message class as a type. You'll want to do this when you're creating customs forms.
The following Automation example gets the current Contacts folder
and adds a new ContactItem object to it.
Set olMAPI = GetObject("","Outlook.Application").GetNameSpace("MAPI")
Set myItem = olMAPI.GetDefaultFolder(olFolderContacts).Items.Add
The following VBScript example adds a custom form to the default
Tasks folder.
Set olMAPI = Application.GetNameSpace("MAPI")
Set myForm = olMAPI.GetDefaultFolder(13).Items _
.Add("IPM.Task.myTask")
The easiest way to return a new AppointmentItem, ContactItem,
JournalItem, MailItem, NoteItem, PostItem,
or TaskItem object directly from the Application
object is to use the CreateItem method with the appropriate
OlItems constant. The following VBScript example uses the
Application object to create a new contact.
Set myContact = Application.CreateItem(2)
If you've used the ActiveInspector property to return an
Inspector object, you can use the CurrentItem property
to return the object that represents the Outlook item displayed
in the inspector. The following Automation example returns the
active Inspector object and displays the name of the item
that the inspector is displaying.
Set olApp = GetObject("","Outlook.Application")
Set currInspect = olApp.ActiveInspector
MsgBox "The active item is " & currInspect.CurrentItem.Subject
To return an Inspector object associated with an Outlook item, use the GetInspector method.
Objects Supported by Outlook Items
Every Outlook item can be analyzed or modified by reading or setting its properties or applying its methods. In addition, every Outlook item can contain other objects that represent more complex qualities or behaviors of the item; for example, there are objects that represent the recipients of the item, the files attached to the item, and the customized pages and controls of the item. The following table describes the objects contained in Outlook items.
Object | Description |
Actions (Action) | Represent specialized actions (for example, the voting options response) that you can perform on an item. |
Attachments (Attachment) | Represent linked or embedded objects contained in an item. |
FormDescription | Represents the general properties of the form for an item. |
Pages | Represents the customized pages of an item. Every Inspector object has a Pages collection, whose count is 0 (zero) if the item has never been customized before. |
Recipients (Recipient) | Represent users or resources in Outlook; generally, recipients are mail message addressees. |
RecurrencePattern | Represents the pattern of incidence of recurring appointments and tasks for the associated AppointmentItem or TaskItem object. |
UserProperties (UserProperty) | Represent the custom fields added to an item at design time. |
For more information about these objects, as well as examples of using them in code, see the corresponding topics in Help.
Events Supported by Outlook Items
The events supported by Outlook items are the key to programming Outlook in VBScript. While designing a form, you can write event procedures in the Script Editor and save that script with the form. You can write procedures that respond to changes in the item or that respond to the user's clicking a control on the form. Within an event procedure, you can use any of the objects exposed by the Outlook type library. For information about the features and restrictions of VBScript, see "Using Automation and VBScript" later in this chapter.
The names of event procedures for items are composed of the word
"Item" followed by an underscore character (_) and the
name of the event (for example, "Item_Open"). Within
an event procedure, you can use the word "Item" to refer
to the object that represents the Outlook item where the event
occurred. The following example adds the date and time that the
Outlook item was opened to the end of the item's subject line.
Function Item_Open()
Item.Subject = Item.Subject & " [opened " & Now & "]"
End Function
For information about adding event procedures to a script in Outlook, see "Using Automation and VBScript" later in this chapter.
Your procedures can respond to some events in Outlook by preventing the default behavior of Outlook from occurring that is, the procedures can interrupt the events. For example, if the user clicks Save on the File menu of an item, you can prompt the user for confirmation and prevent the item from being saved if the user reconsiders. Procedures that interrupt events can be declared as Function procedures; to indicate whether a given event should be allowed to finish, you assign True or False to the function value before the procedure ends. Events that can be interrupted include the following: Close, CustomAction, Forward, Open, Reply, ReplyAll, Send, and Write.
Note If you don't intend to interrupt an event that can be interrupted, you can declare your procedure as a Sub procedure rather than a Function procedure. Procedures that respond to events that cannot be interrupted must be declared as Sub procedures.
Close Event
The Close event occurs when the inspector associated with the
item is being closed. When the event occurs, the inspector is
still open on the desktop. You can prevent the inspector from
closing by setting the function value to False. The following
example automatically saves an item without prompting the user
when the item closes.
Function Item_Close()
If not Item.Saved Then
Item.Save
End If
Item_Close = True
End Function
CustomAction Event
The CustomAction event occurs when one of the item's custom actions
is executed. Both the name of the custom action and the object
that represents the newly created item resulting from the custom
action are passed to the event. You can prevent the custom action's
behavior and prevent the item from being displayed by setting
the function value to False. The following example sets
a property of the response item created by Action1.
Function Item_CustomAction(ByVal myAction, ByVal myResponse)
Select Case myAction.Name
Case "Action1"
myResponse.Subject = "Changed by VBScript"
Case Else
End Select
Item_CustomAction = True
End Function
CustomPropertyChange Event
The CustomPropertyChange event occurs when one of the item's custom
properties is changed. These properties are the nonstandard properties
added to the item at design time. The property name is passed
to the procedure, making it possible for the procedure to determine
which property was changed. The following example enables a control
when a Boolean field is set to True.
Sub Item_CustomPropertyChange(ByVal myPropertyName)
Select Case myPropertyName
Case "RespondBy"
Set cstPages = Item.GetInspector.ModifiedFormPages
Set ctlRespond = cstPages("Page 2").Controls("DateToRespond")
If Item.UserProperties("RespondBy").Value Then
ctlRespond.Enabled = True
ctlRespond.Backcolor = 1
Else
ctlRespond.Enabled = False
ctlRespond.Backcolor = 0
End If
Case Else
End Select
End Sub
Forward Event
The Forward event occurs when the user selects the Forward
action for an item. The newly created item is passed to the procedure.
You can prevent the new item from being displayed on the desktop
by setting the function value to False. The following example
disables forwarding an item and displays a message that the item
cannot be forwarded.
Function Item_Forward(ByVal myForwardItem)
MsgBox "You cannot forward this message."
Item_Forward = False
End Function
Open Event
The Open event occurs when the inspector for an item is being
opened. When this event occurs, the Inspector object is
initialized but not yet displayed. You can prevent the Inspector
object from being opened on the desktop by setting the function
value to False. The following example opens an item in
its inspector and displays the All Fields page.
Function Item_Open()
Item.GetInspector.SetCurrentFormPage "All Fields"
Item_Open = True
End Function
PropertyChange Event
The PropertyChange event occurs when one of the item's standard
properties (such as Subject or To) is changed. The
property name is passed to the procedure, making it possible for
the procedure to determine which property was changed. The following
example disables setting a reminder for an item.
Sub Item_PropertyChange(ByVal myPropertyName)
Select Case myPropertyName
Case "ReminderSet"
MsgBox "You cannot set a reminder on this item."
Item.ReminderSet = False
Case Else
End Select
End Sub
Read Event
The Read event occurs each time the user opens an existing item
for editing. This event differs from the Open event in that Read
is called whenever the user modifies the item in an explorer view
that supports editing or whenever the user opens the item in an
inspector. The following example increments a counter to track
how often an item is read.
Sub Item_Read()
Set myProperty = Item.UserProperties("ReadCount").Value
myProperty.Value = myProperty.Value + 1
myItem.Save
End Sub
Reply Event
The Reply event occurs when the user replies to an item's sender.
The newly created item is passed to the procedure. You can prevent
the new item from being displayed on the desktop by setting the
function value to False. The following example sets the
Sent Items folder for the new item to the folder in which the
original item resides.
Function Item_Reply(ByVal myResponse)
Set myResponse.SaveSentMessageFolder = Item.Parent
Item_Reply = True
End Function
ReplyAll Event
The ReplyAll event occurs when the user replies to an item's sender
and recipients. The newly created item is passed to the procedure.
You can prevent the new item from being displayed on the desktop
by setting the function value to False. The following example
reminds the user that he or she is replying to all the original
recipients of an item and, depending on the user's response, either
makes it possible for the action to continue or prevents it from
continuing.
Function Item_ReplyAll(ByVal myResponse)
myResult = MsgBox ("Do you really want to reply to all original recipients?", _
289, "Flame Protector")
If myResult = 1 Then
Item_ReplyAll = True
Else
Item_ReplyAll = False
End If
End Function
Send Event
The Send event occurs when the user sends an item. You can prevent
the item from being sent by setting the function value to False.
If you interrupt this event, the item's inspector remains displayed
on the desktop. The following example sends an item that has an
automatic expiration date of one week.
Function Item_Send()
Item.ExpiryTime = Date + 7
Item_Send = True
End Function
Write Event
The Write event occurs each time an item is saved
either explicitly, as with the Save or SaveAs method,
or implicitly, as in response to a prompt when the item's inspector
is being closed. You can prevent the item from being saved by
setting the function value to False. The following example
warns the user that item is about to be saved and will overwrite
any existing item and, depending on the user's response, either
makes it possible for the action to continue or prevents it from
continuing.
Function Item_Write()
myResult = MsgBox ("The item is about to be saved. Do you wish to overwrite the _
existing item?", 289, "Save")
If myResult = 1 Then
Item_Write = True
Else
Item_Write = False
End If
End Function
Click Event
The Click event occurs when the user clicks a form control (such
as an ActiveX control or a custom field). You can create as many
Click event procedures as you have controls on a form. The name
of each event procedure is the name of the control (such as "CommandButton1"),
followed by an underscore character (_) and the word "Click."
The following example displays a greeting containing the logon
name of the current user whenever the button named "CommandButton1"
is clicked.
Sub CommandButton1_Click()
MsgBox "Hello " & Application.GetNameSpace("MAPI").CurrentUser
End Sub
Unlike with the word "Item" in other event procedures, you cannot use the name of a control to gain access to the object in a Click event procedure. The properties and methods of the control itself aren't accessible from VBScript.
Note The Message and Note form controls don't support the Click event.
There are two ways to program Outlook objects: remotely from another Office application by using Visual Basic and Automation, or locally in Outlook by using VBScript. You use Automation when you want to control an entire Outlook session; for example, you can copy data from a Microsoft Excel worksheet into a new mail message and send it to a list of recipients, all without leaving Microsoft Excel. You use VBScript when you want to design an Outlookbased solution; for example, you can create a custom mail message form that contains custom controls, fields, and backup processes for a particular workgroup.
Automating Outlook from another Office application is the same as automating any other Office application remotely. You must first reference the Outlook type library; then, use the CreateObject function to start a new session of Outlook, or use the GetObject function to automate a session that's already running. After returning the Outlook Application object by using one of these two functions, you can write code in your controlling module that directly uses the objects, properties, methods, and constants defined in the Outlook type library.
Note If you use Automation to control Outlook, you cannot write event procedures to respond to the events supported by Outlook items.
For more information about using Automation to control one Office application from another one, see Chapter 2, "Understanding Object Models."
For uptodate information about VBScript, see the Visual Basic Scripting Edition Web site at http://www.microsoft.com/vbscript/
If you're creating an Outlookbased solution, you can program Outlook from within your custom forms by writing scripts using VBScript at design time (while you're adding controls and fields to forms after clicking Design Outlook Form on the Tools menu). To view and edit scripts on a form, click View Code on the Form menu in design mode. The Script Editor has templates for all the item events. To add an event template to your script in the Script Editor, click Event on the Script menu, click an event name in the list, and then click Add. The appropriate Sub End Sub or Function End Function statement is inserted, with its arguments (if any) specified. (You cannot add Click event procedures by using the Event command on the Script menu; you must type the Sub End Sub statement for those procedures from scratch.)
Note You can write Sub and Function procedures that don't respond to events, but they won't run unless they're called from valid event procedures.
In Outlook, users cannot run your scripts using Outlook commands. Instead, scripts run automatically in response to events that the user triggers. For example, when the user opens an item based on your form template, the Open event occurs; if an Open event procedure exists, it runs automatically. Only Outlook items and controls on those items support events; folders don't support events.
VBScript is a subset of the Visual Basic language. It's designed to be a small, lightweight interpreted language, so it doesn't use strict types (only Variant). VBScript is also intended to be a safe subset of Visual Basic, so it doesn't include file input/output functions or Automation functions, and it doesn't allow declarations to external functions. The following sections describe the capabilities and restrictions of VBScript in detail.
The following table shows the Visual Basic features and keywords that were included in VBScript.
Category | Feature or keyword |
Array handling | Dim, ReDim
IsArray Erase LBound, UBound |
Assignment | =
Set |
Comment | Rem |
Constants and literals | Empty
Nothing Null True, False |
Control flow | Do ... Loop
For ... Next If ... Then ... Else Select Case While ... Wend |
Conversion | Abs
Asc, AscB, AscW Chr, ChrB, ChrW CBbool, CByte CDate, CDbl, CInt CLng, CSng, CStr DateSerial, DateValue Hex, Oct Fix, Int Sgn TimeSerial, TimeValue |
Date and time | Date, Time
DateSerial, DateValue Day, Month, Weekday, Year Hour, Minute, Second Now TimeSerial, TimeValue |
Declaration | Dim, ReDim
Function, Sub |
Error handling | Err
On Error |
Input and output | InputBox
MsgBox |
Math | Atn, Cos, Sin, Tan
Exp, Log, Sqr Randomize, Rnd |
Objects | IsObject |
Operators | Addition (+), subtraction ( )
Exponentiation (^) Modulus arithmetic (Mod) Multiplication (*), division (/), integer division (\) Negation ( ) String concatenation (&) Equality (=), inequality (<>) Less than (<), less than or equal to (<=) Greater than (>), greater than or equal to (>=) Is And, Or, Xor Eqv, Imp |
Options | Option Explicit |
Procedures | Call
Function, Sub |
Strings | Asc, AscB, AscW
Chr, ChrB, ChrW InStr, InStrB Len, LenB LCase, UCase Left, LeftB Mid, MidB Right, RightB Space StrComp String LTrim, RTrim, Trim |
Variants | IsArray
IsDate IsEmpty IsNull IsNumeric IsObject VarType |
Visual Basic Features Omitted from VBScript
The following table shows the Visual Basic features and keywords that were omitted from VBScript.
Category | Omitted feature or keyword |
Array handling | Array function
Option Base Private, Public Declaring arrays with lower bound <> 0 |
Collection | Add, Count, Item, Remove
Access to collections using the ! character (for example, myCollection!Foo |
Conditional compilation | #Const
#If ... Then ... Else |
Constants and literals | Const
All intrinsic constants Type declaration characters (for example, 256& |
Control flow | DoEvents
For Each ... Next GoSub ... Return, GoTo On Error GoTo On ... GoSub, On ... GoTo Line numbers, line labels With ... End With |
Conversion | CCur, CVar, CVDate
Format Str, Val |
Data types | All intrinsic data types except Variant
Type ... End Type |
Date and time | Date statement, Time statement
Timer |
DDE | LinkExecute, LinkPoke, LinkRequest, LinkSend |
Debugging | Debug.Print
End, Stop |
Declaration | Declare (for declaring DLLs)
Property Get, Property Let, Property Set Public, Private, Static ParamArray, Optional New |
Error handling | Erl
Error On Error ... Resume Resume, Resume Next |
File input and output | All |
Financial | All financial functions |
Object manipulation | CreateObject function
GetObject function TypeOf |
Objects | Clipboard
Collection |
Operators | Like |
Options | Def type
Option Base Option Compare Option Private Module |
Strings | Fixed-length strings
LSet, RSet Mid statement StrConv |
Using objects | TypeName
Collection access using ! character (for example, myCollection!Foo |
Variable names follow the standard rules for naming anything in VBScript. A variable name:
Generally, when you declare a variable within a procedure, only code within that procedure can get to or change the value of that variable; it has local scope and is known as a procedurelevel variable. When you declare a variable outside a procedure, you make it recognizable to all the procedures in your script; it has scriptlevel scope and is known as a scriptlevel variable.
When you're using variables in VBScript, the following limitations apply:
The length of time a variable exists is called its lifetime. A scriptlevel variable's lifetime extends from the time it's declared until the time the script is finished running. A local variable's lifetime begins when its declaration statement is encountered as the procedure begins, and it ends when the procedure concludes. Local variables are thus ideal as temporary storage space while a procedure is running. You can have local variables with the same name in different procedures, because each variable is recognized only by the procedure in which it's declared.
A variable's scope is determined by where you declare it. At script level, the lifetime of a variable is always the same; it exists while the script is running. At procedure level, a variable exists only while the procedure is running; when the procedure exits, the variable is destroyed.
When you automate Outlook by using an Automation object in an application that supports Visual Basic, you can use builtin constants to specify property and argument values. However, when you automate Outlook by using VBScript, you must use the numeric values that the builtin constants represent. For lists of the numeric values of builtin Outlook constants, see "Microsoft Outlook Constants" in Help.
VBScript has only one data type, called Variant. Variant is a special kind of data type that can contain different kinds of information, depending on how the value is used. Because Variant is the only data type in VBScript, it's also the data type returned by all functions in VBScript.
At its simplest, Variant can contain either numeric or string information. Variant behaves as a number when it's used in a numeric context and as a string when it's used in a string context. If you're working with data that resembles numeric data, VBScript treats it as such and processes it accordingly. If you're working with data that's clearly string data, VBScript treats it as such. As in other Microsoft languages, numbers enclosed in quotation marks are treated as strings.
Beyond the simple numeric or string classifications, a Variant can make further distinctions about the specific nature of numeric information, such as information that represents a date or time. When used with other date or time data, the result is always expressed as a date or a time. Variant can contain numeric information ranging in size from Boolean values to huge floatingpoint numbers. These various categories of information that can be contained in a Variant are called subtypes. Usually you'll be able to put the kind of data you want in a Variant, and it will most likely behave in a way that's suited to the data it contains.
The subtypes supported by VBScript correspond to the data types supported by Visual Basic. For information about the data types supported by Visual Basic, see Chapter 1, "Programming Basics."
The VarType function returns a value that indicates the subtype of a variable, giving you information about how your data is stored in a Variant. The following table shows values that can be returned by the VarType function and their respective Variant subtypes.
Subtype | Return value |
Empty | 0 |
Null | 1 |
Integer | 2 |
Long | 3 |
Single | 4 |
Double | 5 |
Currency | 6 |
Date (Time) | 7 |
String | 8 |
Automation Object | 9 |
Error | 10 |
Boolean | 11 |
Variant | 12 (used only with an array of Variant types) |
Non-Automation Object | 13 |
Byte | 17 |
Array | 8192 |
Note The
VarType function never returns the value for Array by itself;
it's always added to some other value to indicate an array of
a particular type. The value for Variant is returned only after
it's 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 that property.