Tech Note 24: Automating Excel, Word, Excel, Outlook and other COM aware apps

January 29, 2007

© NS BASIC Corporation. All rights reserved.



One of the most powerful features of Windows is its ability to have other apps use the interfaces built into applications. Part of COM, this ability is built into many applications, including Excel, Word, Outlook, Access and others.

NS Basic/Desktop lets you take advantage of this. By creating an object for the application, you can use many of the same functions and data elements that the applications use themselves. You'll be able to write programs that extract data, reformat information or create new data in each of these applications.

There are some sample programs included with NS Basic/Desktop that show you how to do this.

Example: Automating Outlook

Let's have look at the MS Outlook program to see how it works. One of the things the program does is extract the To Do list and display it in a message box. Here is the code that does this:

First, let's create an object for Outlook:

    Set objOutlook = CreateObject("Outlook.application")
(If you want to do Excel, it would be "Excel.application", etc. The Microsoft apps are consistantly named. For other packges, you may need to check what they are called.)

Now that we have the object created, let's see what we can do with it. The Microsoft Office apps have a built in Object Browser that lets you see what is available. Launch Outlook and hit Alt F9. It will bring up a window labelled "Microsoft Visual Basic". Once launched, type F2 to bring up the Object Browser. Select 'Outlook' in the top ComboBox. Your screen should look like this:

This exposes all the classes and members in the Outlook Object. There is a bewildering array of possibilities. Unless you are already familiar with them, you'll want to spend some time on Microsoft's site getting more documentation.

Now that we have the object, let's get some objects within it. We want to get the object ('MyItems'), which is the Items object within our Tasks Outlook Folder ('olFolderTasks')

    'See Outlook VB documentation for NameSpace and MAPI    
    Set objNameSpace = objOutlook.GetNameSpace("MAPI") 
    Set objFolder = objNameSpace.GetDefaultFolder(olFolderTasks)
    Set MyItems = objFolder.Items

Now that we have the tasks in the object, we can simply iterate through it, select the ones we want, and concatenate them into the string 'strText'.

    For Each CurrentTask in MyItems
        If CurrentTask.DueDate <= Now And CurrentTask.Complete = False Then
	        strText = strText & CurrentTask.Subject & vbCrLf
        End If
    Next

Finally, we display the result in a message box.

    If strText > "" Then
        MsgBox strText, vbExclamation, "   TODAYS TASKS   "
    Else
        MsgBox "There are no tasks for today in Outlook", vbInformation,"   TODAYS TASKS   "
    End If

How it looks in NS Basic/Desktop: