Fundamentals for writing VBA for Outlook macros
My columns since January 2000 about writing practical Visual Basic for Applications (VBA) code for Microsoft Outlook 2000 have covered a lot of ground: automatic message processing, dates and tasks, handling recipients, and many more subjects. Some readers have recently written that they're just getting started with Outlook VBA, though, so this month I want to review some basics.
A little history first: Outlook 2000 is the first version of Outlook to let you write VBA macros and run them inside the program. To control Outlook 98 and Outlook 97 with VBA, you had to write a macro in some other VBA environment, such as Microsoft Word or Microsoft Excel, then run the macro from that program. Outlook 98 and Outlook 97 also didn't include the application-level events that let you run code when you perform common tasks such as starting Outlook, sending a message, or switching between folders. Although Outlook 98 introduced a customizable toolbar, it didn't let you create a toolbar button to run your own code.
Outlook 2000, therefore, is a real breakthrough for power users, administrators, and developers who want to customize the program. Just as the addition of a macro language to Excel helped turn it into the tool of choice for financial analysis, the ability to program so many aspects of Outlook has strengthened its popularity. Software developers have used the new capabilities in Outlook 2000 to produce programs to back up Outlook data, automatically compress attachments in outgoing messages, improve Outlook's handling of mail sent on behalf of other users, work with other users' Calendar folders, and synchronize Microsoft Exchange Server mailbox data to public folders. Individual users use VBA code to refile incoming messages, create related items, perform custom printouts, and customize the way Outlook handles outgoing items and reminders. Outlook 2002 extends VBA to add new objects, properties, and methods that we'll explore in future columns.
If Outlook's programmability raises a red flag, keep in mind that Outlook-related email viruses don't use VBA but rather VBScript, which isn't a secure programming language. You can't digitally sign VBScript code, but you can digitally sign VBA projects and set macro security to let only signed code run. At the conclusion of this column, I show you how to secure your VBA code.
The VBA Editor
Outlook has the same VBA editor as other Microsoft Office programs, so if you've ever worked with Word or Excel macros, the editor should look familiar. To open the editor, which Figure 1, page 88, shows, click Tools, Macro, Visual Basic Editor from Outlook's main menu, no matter what folder you're in. Or you can press Alt+F11.
The biggest difference between VBA for Word or Excel and VBA for Outlook is that the latter includes no macro recorder. You must provide all the code. Fortunately, Web sites and several active discussion forums offer code fragments that you can use in your applications. I maintain an extensive collection of links to Outlook VBA code and other resources at http://www.slipstick.com/dev/vb.htm. You can also download code samples from earlier Outlook VBA on Demand articles at Windows 2000 Magazine's Web site (the first Outlook VBA on Demand column is at http://www.win2000mag.com, InstantDoc ID 7677).
If you download a code sample that comes as a .bas file, you can click File, Import File to import the file into VBA. The import facility puts the code in a new module under Project1.Modules.
If the code needs to run in the built-in ThisOutlookSession module to take advantage of application events, copy it from the imported module into the ThisOutlookSession module, which you'll find under Project1.Microsoft OutlookObjects. Restart Outlook to ensure that the macros in ThisOutlookSession that use application events run automatically.
If you write a new macro that you plan to run from a toolbar button, or copy such a macro from a discussion list, you can either put it in the built-in ThisOutlookSession module or create a new code module with the Insert, Module command. I like to organize modules by topic so that I have all code that deals with task items in one module, code for working with folders in another, and so on. If you collect related macros in one module, you can easily make a backup copy of that module by using the File, Export command to save the module as a .bas file.
If you want to share your macros with other people, you can give them the exported .bas file. They can then import the file into their own Outlook VBA project. If you want to give someone all your Outlook VBA code, you can give him or her a copy of your vbaproject.otm file, which contains all the code that you see in Outlook VBA. You can't back up or copy this file while Outlook is running.
Code on Demand
You can use Outlook VBA to write two types of code. One type of code runs automatically from the ThisOutlookSession module. You can find many examples of this type of code in earlier Outlook VBA on Demand columns. The other type of code runs on demand when you click a button that you've added to the toolbar or press Alt+F8 to select a macro from the Macros dialog box.
Not every procedure you write is eligible for a toolbar button. To be able to run a procedure as a macro from the toolbar or the Macros dialog box, you must ensure that it meets these criteria:
- The macro is a subroutine, not a function.
- The macro is a Public subroutine. (Public is the default for subroutines that you don't label Public or Private.)
- The macro doesn't have any arguments.
For example, this procedure would work fine as a toolbar macro:
Sub HelloWorld()
MsgBox "Hello World!"
End Sub
But these wouldn't:
Private Sub HelloWorld()
MsgBox "Hello World!"
End Sub
Public Sub Hello(strWho)
MsgBox "Hello " & strWho
End Sub
Public Function Hello()
strWho = _
InputBox("Say hi to whom?")
MsgBox "Hello " & strWho
Hello = strWho
End Sub
To add a macro to the toolbar, choose View, Toolbars, Customize from the main Outlook menu. On the Commands tab in the Customize dialog box, select Macros from the Categories list. You'll see a list of macros on the right. Copy the desired macro to the toolbar or to an Outlook menu. Right-click the newly created toolbar button or menu command to customize the name, button, and other features.
Adjusting the Security Level
After you've written some VBA code, you might see a message when you start Outlook telling you that the macros can't run because of your security settings or asking you to authorize the macros. Outlook's macro security level determines which message you might see. You can change the security level on the Security dialog box that Figure 2 shows. From the main Outlook menu, select Tools, Macro, Security to open the dialog box.
If you want to use High security, you need to digitally sign your project, much as you might digitally sign an email message. Office 2000 includes the selfcert.exe file, which lets you create a self-signed certificate for signing projects. After you run this program and follow its prompts, you'll have a certificate that you can use to sign any VBA project. To use the self-signed certificate to sign your Outlook VBA project, choose Tools, Digital Signature in the VBA editor. If you don't see the Digital Signature command, you need to run Office Setup to install that option. For more details, read the Microsoft Developer Network (MSDN) article "How to Prevent the VBA Macro Security Warning in Microsoft Outlook 2000" (http://msdn.microsoft.com/library/techart/oldigitalsignature.htm). Note that Microsoft cautions that because no Certificate Authority (CA) backs the self-signed certificate, you should use it to sign only your personal VBA projects.
Ready to get started? Download some code samples and get going.
Great article.
One comment. At the end of the article was written, "Ready to get started? Download some code samples and get going."
It would be really cool to have some good links where to find the code to download.
Hi
I am new to VBA programming, can tell me how you would open a web page in outlook, i have created the following macro and its works fine
but when the web page opens all the colour is missing and links don't work. How can you get the links to work and have the colours displayed.
Many Thanks
skandar
Sub Send_weather()
Send_Message "http://www.msn.com", "skandar@zetacontrols.co.uk"
End Sub
Private Sub Send_Message(xURL, email)
Dim objIE As Object
Dim objOL As New Outlook.Application
Dim objMail As MailItem
Set objIE = CreateObject("InternetExplorer.Application")
objIE.Navigate (xURL)
Do While objIE.Busy
Loop
Do While objIE.Document.ReadyState <> "complete"
Loop
Set objOL = New Outlook.Application
Set objMail = objOL.CreateItem(olMailItem)
objMail.To = email
objMail.Subject = "From Street Map - " &
objIE.LocationName
'objMail.HTMLBody = objIE.Document.Body.innerHTML
objMail.HTMLBody = "" &
objIE.Document.Body.outerHTML
'objMail.HTMLBody = ""
objMail.Send
Set objMail = Nothing
Set objOL = Nothing
Set objIE = Nothing
End Sub
This is JUST what I needed. Thank you!!
This looks great! Thanks Sue.
I am looking for a way to collect email accounts from a form that I have on my website.
My form sends me emails from customers who want to stay current with our software updtaes. Right now I recieve emails that I copy and paste adresses from. This worked ok at first, but now we are recieving such a high volume of requests that it has become a tedious endeavor.
Can I write a macro that will strip these email addresses out and write them to a text file. I am looking for a better alternative than what I have going right now.
I want to add a button to my toolbar to do Find Related messages. It is possible to get this by adding the button in Outlook 2002 and then upgrading. However now I have a new Windows profile. Is there a way to add it from the mEnus or must I use a macro ?
good article ..please tell me how to write macros for outlook ...please send me tutorials or the link of tutorials
vipul, for more tutorials like this one, see http://www.outlookcode.com/d/vb.htm#tutorials
For a great tutorial on practical, business uses of outlook try:
http://www.321books.co.uk/ebooks/outlook-vba-tutorial.htm
Hello, Sue I have a background with VBScript and VB6.0, but I don't understand the difference between these application programs and VBA. Are the subroutines that you talk about here no compileable under the VB6.0 environment?
Great article. Is there a way to turn off the automatic compression of outgoing message attachments?
Ive been trying to work out code that saves an opened email message as a text file in a certain folder with a the name temp, this file will be getting overwtritten constantly. can anyone help?
Thanks in advance
I need help please, i need to measure the response time (service level agreement) so i wish to take the time between the request and the answer. How can i do that for every client?
AM SENDING DATA IN OUTLOOK AND MY LANGUAGE IS VBSCRIPT. NOW AM USING THE FIELD CHOOSER TO GET THE CONTACTS BUT WHEN I TRY SENDING THE DATA, ITS TELLING ME THE DESTINATION CC,TO, IS NULL.
PLEASE NOTE IN THIS ONE BUTTON FOR SEND ITS SAVING DATA IN ACCESS. AM JUST USING THE FIELD CHOOSER TO GET THE CONTACTS FROM THE CONTACT LIST.I DISCOVER THAT THIS CONTROL IS NOT BEING RECOGNISED
I am importing the email details from Microsoft Office Outlook 2003. But every time a detail is used from my messages in the inbox, it warns me that a virus may be trying to access my messages and I have to click yes(to allow the program to access it) for every detail that I import. I've tried signing my project but still no success.
I am trying to catch an email when it arrives into Outlook 2002 and then parse the email and save the data (From, To, Subject, etc.) into a SQL Server 2000 DB and am having trouble.
The code above for getting the output of a webpage is excelent... Thanks you.