Special Edition Using Microsoft Office Outlook 2003
To create a script to run behind your form, open the form in design mode. Select Form, View Code to display the Script Editor, shown in Figure 32.27. The Script Editor is really nothing more than a slightly enhanced Notepad application, but you can still write very powerful scripts behind Outlook forms. Figure 32.27. The Script Editor is not much more than a Notepad application with custom menus.
Proper Syntax
There are a few things to know before you start writing scripts behind Outlook forms. First, you must know a little about how scripting works. In Outlook, all script should be contained inside wrappers. These wrappers can take two forms: subroutines and functions. A subroutine is a group of code that runs as a whole. You start the subroutine, step through each line of code, and end the subroutine. A function is a subroutine that returns a value. The following is an example of a subroutine: Sub cmdButton_Click() Dim txtName Dim objNS Dim objFolder Dim objContactItem txtName = "John Spencer" Set objNS = Application.GetNamespace("MAPI") Set objFolder = objNS.GetDefaultFolder(10) Set objContactItem = objFolder.Items.Add(2) objContactItem.FullName = txtName objContactItem.Close 0 Set objContactItem = Nothing Set objFolder = Nothing Set objNS = Nothing End Sub This code runs, or fires, in response to the click of the command button named cmdButton. All the variables are dimensioned or declared at the beginning of the subroutine. Although it isn't absolutely necessary in VBScript, it's helpful to keep track of all of your variables in one place. The last three lines of code release all the object variables. Releasing an object variable frees any memory the variable was using during code execution. You should always release your object variables when you're done with them to free any memory they might be holding. The middle section of code creates a variable for the Outlook namespace. The GetDefaultFolder method is then called on that namespace variable to return the Contacts folder. A contact item is added to the Contacts folder, and the full name of the contact is populated. The Contact item is then closed, changes are saved, and all object variables are released. Here are some key elements to remember when using VBScript code:
In addition to some basic code conventions, it's important to understand the proper syntax for referencing Outlook items, their properties, and methods. The single best source of information within Outlook is the Outlook Object Library Help. You can access this help by selecting Help, Microsoft Outlook Object Library Help from the Script Editor to display Figure 32.28. Figure 32.28. Use the Object Library Help to understand objects, properties, and methods.
When you launch the Object Library Help, you'll see a graphical representation of all Microsoft Outlook Objects. Clicking on any one of these objects takes you to the Help topic for the object. For instance, to view all the properties and methods associated with an appointment item, select the Item object. Then select the Appointment item object. Click on the links for Properties, Methods, and Events to display a listing of these items. If you want more information about any of these properties, methods, or events, click the individual item in the drop-down list and Outlook will display the help topic for that item. There are two built-in variables you can use in code behind an Outlook form. The Application object always represents the current instance of the Outlook application. You don't need to declare any variables to use the Application object. The other built-in variable is the Item variable. This variable always represents the current Outlook item. It doesn't matter whether the item is an appointment, contact, email message, task, note, or journal entry. In addition to the two built-in object variables, it's helpful to understand a few other terms before you begin writing code. Many of the code samples you'll see in this chapter reference the Inspector object. An inspector is the actual window used to display the Outlook form. It's very much like the frame of a picture. The picture is what you're interested in, but you need the frame to display the picture. Your code might use the GetInspector method of the Item object to work with controls on an Outlook form. The Namespace object is a container for all of your Outlook folders. It has methods such as GetDefaultFolder, which can return any of the built-in folders in Outlook. The default namespace in Outlook is MAPI; in fact, it's the only Namespace that's available. To reference the Namespace object, use the following syntax: Set objNS = Application.GetNamespace("MAPI") Retrieving and Setting Field Values
As previously described, a control is a container for a field. When working with Outlook items in code, it's better to set the field value than the control value. To reference a standard field in an Outlook item, reference the item (usually with the built-in Item variable), add a period, and then type the field name. To set the subject of a message item, use the following syntax: Item.Subject = "Department Meeting" If you're working with a custom form, chances are that you've created custom fields to store data. Referencing a custom field requires a different syntax. To reference a custom field, use the following syntax: Item.UserProperties("CustomerCode") = "ABCBrewing" The previous syntax shows you how to set a field value. To retrieve a field value, set a variable equal to the field value: txtCompanyName = Item.UserProperties("CompanyName") Working with Control Values
On occasion, you might want to work directly with the value or properties of a control. For instance, you might want to add an unbound text box control to your form. An unbound control will not transmit data when the custom form is closed or sent, but it can display data while a form is running. A typical use of an unbound control is to hold a temporary piece of data. To reference a control on an Outlook form, you must know two pieces of information: the control's name and the name of the page that contains the control. Use the following code sample to enable a text box control named Contract Length on a one-page message form: Set objPage = Item.GetInspector.ModifiedFormPages("Message") Set objControl = objPage.Controls("Contract Length") objControl.Enabled = 1 NOTE When setting true and false values in VBScript, 1 represents true and 0 represents false.
Working with Control Events
In Visual Basic, you can work with a variety of events for each control. A text box control has a click event, a before update event, and a change event. When working with Outlook forms, you can access events only on unbound controls. So, after you bind a field to a text box, you can no longer call the click event of that text box. To add code in response to the click event of a command button, use the following syntax: Sub cmdCreateMail_Click() Set objNS = Application.GetNamespace("MAPI") Set objFolder = objNS.GetDefaultFolder() Set objItem = objFolder.Items.Add() objItem.To = "Robert Cardoza" objItem.Subject = "Meeting Minutes Overdue" objItem.Body = "Please submit your meeting minutes today." objItem.Send Set objItem = Nothing Set objFolder = Nothing Set objNS = Nothing End Sub The preceding code sets a reference to the Namespace object, and then sets a reference to the Outbox folder. A new item is created in the Outbox folder and the To, Subject, and Body properties are set through code. When all the necessary properties are set, the email item is sent. The last three lines of code before the End Sub line release all your object variables. It's always best to release your object variables to properly clean up your code. Events
Outlook forms support a variety of events. You can write code that is triggered whenever an event occurs. The events supported in Outlook forms are seen in Table 32.1.
All events available within an Outlook form are accessible through the Script Editor. To add an event to your form, select Script, Event Handler to display Figure 32.29. Figure 32.29. Use the Insert Event Handler dialog box to choose your event.
Choose the event you need and click Add. Your event will be added to the Script Editor. If variables are passed to the event, they will be included. Consider two complete events: CustomPropertyChange and BeforeDelete. Each of these events is passed a variable when it fires. You can add code to any of these events to control their results. The following code listing uses the CustomPropertyChange event to set the value of a field based on the value of another field. Sub Item_CustomPropertyChange(ByVal Name) Select Case Name Case "Company Name" If Item.UserProperties("Company Name") = "ABC Bakery" then Item.UserProperties("Industry") = "Baking" Else Item.UserProperties("Industry") = "Non Baking" End If End Select End Sub Programmatically Publishing a Form
It's possible to automate the publishing of a form through code. To publish a form to a forms library, use the following code: Sub PublishForm() Dim objNS Dim objFolder Dim objItem Dim objNewForm Set objNS = Application.GetNamespace("MAPI") Set objFolder = objNS.GetDefaultFolder(6) 'Inbox Set objItem = Application.CreateItem(0) 'Create a mail item Set objNewForm = objItem.FormDescription 'Get the new item's definition objNewForm.Importance = 2 'Make the item high importance objNewForm.Name = "HighPriorityEmail" 'Name your new form objNewForm.DisplayName = "High Priority Email" 'Enter a display name for your 'form objNewForm.PublishForm 3, objFolder 'Publish to a folder forms 'library objNewForm.Close 1 'Discard changes End Sub This code creates a new email, sets the priority to high, and publishes the form with a form name of HighPriorityEmail and a display name of High Priority Email. The form is then published to the folder forms library. You can also publish a form to the organizational forms library by changing the constant in the line objNewForm.PublishForm 3, objFolder from 3 to 4. Security Concerns
In the aftermath of the I Love You and Melissa viruses, Microsoft introduced new security features into Outlook. The security features had two main components: an attachment block and an object model guard. The Outlook Object Model, the basis for all Outlook development, enforces restrictions on the address book and on automatic sending of email. These restrictions inform the user of certain programmatic access to the Outlook Object Model and require the user to approve such actions. If you execute the following lines of code, you'll trigger the Object Model Guard: Sub SendMail() Dim objItem Set objItem = Application.CreateItem(0) objItem.To = "sam@spade.com" objItem.Subject = "Meeting Schedule" objItem.Body = "Please check your schedule to determine if " objItem.Body = objItem.Body & "you can attend a meeting on August 2nd." objItem.Send Set objItem = Nothing End Sub When the line objItem.Send is executed, you'll see the warning shown in Figure 32.30. You must wait a full 10 seconds before you can approve programmatic sending of the email. Figure 32.30. You must approve programmatic sending of email.
In addition to guarding programmatic sending of email, the Object Model Guard also protects the email addresses you store in Outlook. If you attempt to access the email addresses stored in your Outlook Contacts folder, you'll receive the warning displayed in Figure 32.30. You can approve access to your Contacts folder for 1, 2, 5, or 10 minutes. Both components to the Object Model Guard are designed to inform you if a virus has infected your system and is trying to send out emails without your knowledge. Although the Object Model Guard greatly reduces the capability of a virus similar to Melissa to propagate without your knowledge, it also puts a damper on Outlook programming. After all, one of the reasons you might want to write code behind an Outlook form is to send an email in response to a command button click. This type of code will raise the Object Model Guard. There are two main methods you can use to work with the Object Model Guard. One method is to use Microsoft Exchange Server and deploy the Administrative Options Package. This method utilizes a custom form in an Exchange public folder to allow or disallow programmatic access based on your Exchange user account. The advantage to this method is that an administrator can specify which users can bypass the Object Model Guard and which cannot. The disadvantage is that you enable or disable the Object Model Guard completely. You cannot disable the Object Model Guard for only one custom form. If a user is permitted to send email programmatically through the Administrative Options Package, a virus that infects the user's machine has unfettered access to the user's Outlook. The second method you can use is a third-party dynamic link library (DLL) called Redemption. Once registered on a user's system, Redemption can be used within code to create safe objects that are immune to the Object Model Guard. The main advantage to Redemption is that you use it only in custom forms that would trigger the Object Model Guard. Using Redemption in a custom form does not make your Outlook vulnerable to viruses; it merely enables your custom form to bypass the security prompts. |