Friday, November 11, 2011

The Application Object


The Application Object

The Application object sits at the top of the object model and represents the entire Outlook application. The Outlook Application object has several purposes:
  • As the root object, it enables you to reference other objects in the Outlook object hierarchy.
  • It provides methods such as CreateItem and CreateObject so that you can create new items and reference them without moving through the object hierarchy.
  • It provides methods for directly referencing the active Outlook window or form.
For a complete list and description of the methods, properties, and events for the Application object, see Microsoft Outlook Visual Basic Reference Help. Also see the Visio document entitled "Outlook 2002 Object Model Extended View" in the Outlook 2002 Object Model folder under the Visual Basic for Applications folder under the 4. Beyond the Basics folder. This object model diagram shows the properties, methods, and events for every object in the Outlook object model.
Open the Application object item in the VBScript Samples folder to work directly with this code in Outlook.

Application Object Methods

This section covers the ActiveExplorerActiveWindowAdvancedSearchCopyItemCreateItemCreateObject, and GetNameSpace methods.

Returning the Active Window

You can use the ActiveWindow method of the Application object to return the topmost active Outlook window. The ActiveWindow method returns either an Explorer or an Inspector object, depending on the actual active window.
‘Get the Active Outlook Window
‘The ActiveWindow object is the topmost window in the running
‘Outlook instance
Sub GetOutlookActiveWindow_Click
    If TypeName(Application.ActiveWindow) = "Inspector" Then
        MsgBox "The active window is an inspector", vbInformation
    Else
        MsgBox "The active window is an explorer", vbInformation
    End If
End Sub
The following example sets the MyExplorer object to the currently active Outlook Explorer window, displays a message that indicates the active window type, and then redisplays the item window when the ShowOutlookActiveExplorer control is clicked:
Sub ShowOutlookActiveExplorer_Click
    Set MyExplorer = Application.ActiveExplorer
    MyExplorer.Display
    GetOutlookActiveWindow_Click()
    Item.Display
End Sub

Creating a Standard Item

You can use the CreateItem method of the Application object to create and return Outlook standard items such as a Message item, a Post item, or an Appointment item. The following example creates a Message item using the default editor and displays it when CreateAMailMessageis clicked:
Sub CreateAMailMessage_Click
    Set MyItem = Application.CreateItem(0)
    MyItem.Display
End Sub
The next simple example creates an HTML message.
Sub CreateHTMLMessage_Click
    Const olMailItem = 0
    Set myItem = Application.CreateItem(olMailItem)
    myItem.shtmlLBody = ""
    myItem.Display
End Sub
It’s useful to know that you can also create a Word Envelope message in code. The following example uses the CreateObject method to launch Word and display a Word Envelope message. From the standpoint of the message body, Word Envelope messages are equivalent to HTML messages.
‘Creates a Word Message item and displays it
Sub CreateAWordMessage_Click
    Const wdNewEmailMessage = 2
    Dim objApp,objMsg 
    Set objApp = CreateObject("Word.Application")
    Set objMsg = objApp.Documents.Add(,,wdNewEmailMessage)
    objApp.Visible = True
    objApp.ActiveWindow.EnvelopeVisible = True
End Sub
The following table lists the numeric values you use as arguments for the CreateItem method. You can also copy the CONST declarations in the Enum OlItemType section of the Outlook Constants item in the VBScript Samples folder and paste them into your code.
Type of ItemValue
Appointment
1
Contact
2
Distribution List
7
Journal
4
Mail Message
0
Note
5
Post
6
Task
3
For more information about creating custom items, see "Items Collection Methods" later in this chapter.

Creating an Automation Object

You can use the CreateObject method of the Application object to create Automation objects, such as Microsoft Excel, Microsoft Access, or Microsoft Word objects. You can also use the CreateObject method to create instances of custom ActiveX DLLs that extend the functionality of Outlook. The following example uses the CreateObject method to create an instance of Excel, adds a workbook, and then renames the first sheet in the workbook to Outlook CreateObject Example:
‘Launch Excel with CreateObject
Sub LaunchExcel_Click
    Dim xLApp ‘As Excel.Application
    Dim xLSheet ‘As Excel.Worksheet
    Set xLApp = CreateObject("Excel.Application")
    If xLApp Is Nothing Then
        MsgBox "Could not create Excel Application", vbCritical
        Exit Sub
    End If
    xLApp.Workbooks.Add
    Set xLSheet = xLApp.Sheets(1)
    xLSheet.Name = "Outlook CreateObject Example"
    ‘Make the Excel Application window visible
    xLApp.Visible = True
End Sub
When you are writing Automation code for VBScript in Outlook forms, you can expedite the development process by using the VBA Editor in Outlook to write the code and then pasting the code into VBScript. As noted in the example above, you must place comment marks before the As keyword in the object type declarations, or VBScript will raise an error. The beauty of this approach is that you have all the IntelliSense features of the VBA Editor at your disposal, including auto list members, syntax checking, parameter information, quick information, and code formatting. Before you begin, set references to the appropriate object libraries by using the Tool menu’s References command in the VBA Editor window.

Copying an Item from the File System

The CopyItem method is new to Outlook 2002. It lets you copy an item from the File System to an Outlook folder. The following code example creates a Word document in the temporary folder, adds some text to the document, and then uses the CopyItem method to copy the document to the user’s Inbox folder. Note that the CopyItem method accepts a string for the path to the destination folder instead of a MAPIFolder object.
Sub CopyItemToInbox_Click
   Dim objWord 'As Word.Application
   Dim objDoc 'As Word.Document
   Dim objSelect 'As Word.Selection
   Dim objDocItem 'As DocumentItem
   Set objWord = CreateObject("Word.Application")
   Set objDoc = objWord.Documents.Add
   Set objSelect = objWord.Selection
   objSelect.TypeText "Word document created with Automation"
   strPath = GetTempDir & "\test.doc"
   objDoc.SaveAs strPath
   Set objDocItem = Application.CopyFile(strPath, "Inbox")
   objDocItem.Display
   Set objWord = Nothing
End Sub

Returning a MAPI NameSpace Object

You can use the GetNameSpace("MAPI") method of the Application object to return the MAPI message store.
In the following example, the GetNameSpace method returns the NameSpace object. The Offline property of the NameSpace object is then used to display a message box indicating whether the user is on line or off line.
Sub CommandButton1_Click()
    Dim MyNameSpace As NameSpace
    Set MyNameSpace = Application.GetNamespace("MAPI")
    If MyNameSpace.Offline Then
        MsgBox "You are offline!", vbInformation
    Else
        MsgBox "You are online!", vbInformation
    End If
End Sub
The only data source currently supported is MAPI, which allows access to all Outlook data stored in MAPI. For this reason, theGetNameSpace method must always appear in Outlook as GetNameSpace("MAPI").

Creating Office Objects

The Application object has several child objects that are actually members of the Microsoft Office Object Model. For example, the Application object contains member objects for the Office AnswerWizard, Assistant, COMAddIns, and LanguageSettings objects. The following code example uses an animated Assistant to display the LanguageID settings for the Outlook Application object.
‘Display the LanguageSettings
Sub DisplayLanguageSettings_Click
    Const msoLanguageIDInstall = 1, msoLanguageIDUI = 2
    Const msoLanguageIDHelp = 3
    Const msoAnimationListensToComputer = 26
    Const msoModeModal = 0, msoButtonSetOK = 1, msoIconTip = 3
    On Error Resume Next
    Dim oa ‘As Office.Assistant
    Dim bln ‘As Office.Balloon
    strMsg = "The following locale IDs are registered " _
        & "for this application:" & vbCr & "Install Language - " & _
        Application.LanguageSettings.LanguageID(msoLanguageIDInstall) _
        & vbCr & "User Interface Language - " & _
        Application.LanguageSettings.LanguageID(msoLanguageIDUI) _
        & vbCr & "Help Language - " & _
        Application.LanguageSettings.LanguageID(msoLanguageIDHelp)
    Set oa = Application.Assistant
    oa.On = True ‘Assistant not available
    If Err Then
        MsgBox strMsg, vbInformation
    Else
        oa.Visible = True
        Set bln = oa.NewBalloon
        bln.Heading = "Language Settings"
        bln.Mode = msoModeModal
        bln.Button = msoButtonSetOK
        bln.Icon = msoIconTip
        bln.Text = strMsg
        bln.Show
        oa.Animation = msoAnimationListensToComputer
    End If
End Sub 

Creating a Programmatic Search

The ability to create a programmatic search using the AdvancedSearch method of the Application object is new to Outlook 2002. AdvancedSearchreturns a Search object, which in turn contains a Results object that you can use to iterate over the items contained in that Results object. A Results object is identical to an Items collection object. You use the AdvancedSearch method in conjunction with the AdvancedSearchComplete event for the Application object. When the AdvancedSearchComplete event fires, you’ll know that the Search object for your query is available for further processing. Assign a Tag value in your call to AdvancedSearch so that you can identify the correct Search object in the AdvancedSearchComplete event. See Chapter 9, "Raise Events and Move to the Head of the Class," for additional details on the AdvancedSearchComplete event and Chapter 14, "Creating COM Add-Ins with Visual Basic," for a discussion of the sample Search add-in.
AdvancedSearch takes four arguments, two of which are enigmatically explained in Outlook Visual Basic Help. Here is the syntax for a call toAdvancedSearch:
Set objSearch = objApp.AdvancedSearch(Scope, Filter, SearchSubfolders, Tag)
Both the Scope and Filter arguments can be understood in the context of Microsoft Exchange 2000 Web Storage queries. Although you don’t have to run against an Exchange 2000 server to use AdvancedSearch, you should consult the Exchange SDK to gain a complete understanding of Web Storage System SQL. The Exchange SDK is available on the Web at http://msdn.microsoft.com/exchange and is also included on this book’s companion CD. See the section entitled "Web Storage System SQL."
Fortunately, there are quicker and less painful ways to get up to speed with Filter and Scope syntax. You can use an undocumented Registry key to display a Query Builder page on the Filter dialog box associated with the View Summary dialog box. (See Figure 11-1.) After you use the Query Builder to construct your query, you can then copy the Filter syntax displayed on the SQL page and paste it into your code. Do not attempt to add the Query Builder page Registry setting unless you are familiar with the Microsoft Windows Registry Editor.
Figure 11.1 - The undocumented Query Builder page on the Filter dialog box.

To display the Query Builder page on the Filter dialog box

  1. Click Start, point to Run, type Regedit in the Run dialog box, and then click OK to launch the Windows Registry editor.
  2. In the Registry tree, navigate to HKEY_CURRENT_USER\Software\ Microsoft\Office\10.0\Outlook.
  3. Select New from the Edit menu, and then select Key from the New submenu.
  4. Type QueryBuilder in the Key edit box. Regedit will suggest New Key #1, but you should replace that key name with QueryBuilder.

To build a filter using the Query Builder page on the Filter dialog box

  1. In Outlook, select Current View from the View menu and then select Customize Current View from the Current View submenu.
  2. Click the Filter button on the View Summary dialog box.
  3. Click the Query Builder page on the Filter dialog box.
  4. Use the Query Builder interface to build your query. When you construct a filter, you actually build a WHERE clause without the WHERE keyword. Notice that you can use the logical AND or logical OR operator to develop the query and move clauses up or down.
  5. Click the SQL page shown in Figure 11-2 on the Filter dialog box, and clear the Edit These Criteria Directly check box. Once you clear the check box, you can copy the query by selecting it and pressing Ctrl+C to copy to the Clipboard.
  6. Because you don’t want to modify the view, click Cancel to dismiss the Filter dialog box. Then click Cancel again to dismiss the View Summary dialog box.
Once you have constructed your Filter string, the rest of the process is relatively straightforward. The Scope argument can use either an unqualified folder name such as Inbox, Drafts, Tasks, or a folder path in a Web Storage System SQL Scope clause. SearchSubFolders is Boolean and will work only in a Mailbox or PST store. If you’re searching a public folder, you can search only one folder at a time. This is a built-in limitation of the MAPI Public Folder store. As stated previously, you should use the AdvancedSearchComplete event to process the Search object returned byAdvancedSearch. This next code example shows you how to construct a programmatic search and displays the user form shown in Figure 11-3 when the search is complete.
Figure 11.2 - Copy a Filter string from the SQL page of the Filter dialog box to provide the Filter argument for the AdvancedSearch method.
Sub ShowSearch()
    Dim olApp As Outlook.Application
    Dim objFolder As MAPIFolder
    Dim objSearch As Search
    Dim strFolderPath As String, strScope As String, strFilter As String
    Set olApp = New Outlook.Application
    ‘Create a MAPIFolder object for Inbox
    Set objFolder = olApp.GetNamespace("MAPI") _
       .GetDefaultFolder(olFolderInbox)
    ‘Get the folder path
    strFolderPath = objFolder.FolderPath
    ‘Build a scope string
    strScope = "SCOPE (‘shallow traversal of " _
       & AddQuotes(strFolderPath) & "‘)"
    ‘Build a filter string (WHERE clause without the WHERE)
    strFilter = AddQuotes("urn:schemas:mailheader:subject") _
       & " LIKE ‘RE:%’"
    ‘Create the Search object by calling AdvancedSearch
    Set objSearch = _
       olApp.AdvancedSearch(strScope, strFilter, False, "RESearch")
End Sub

Private Sub Application_AdvancedSearchComplete _
    (ByVal SearchObject As Search)
    On Error Resume Next
    Dim objResults As Results
    Dim objItem As Object
    Dim objListItem As Object
    Dim frmAdvancedSearch As New frmSearch
    If SearchObject.Tag = "RESearch" Then
        frmAdvancedSearch.ListView1.ListItems.Clear
        ‘Create the Results object
        Set objResults = SearchObject.Results
        ‘Create a reference to first item in Results object
        Set objItem = objResults.GetFirst
        If Not objItem Is Nothing Then
            Do
                ‘Add item to the ListView control
                Set objListItem = _
                   frmAdvancedSearch.ListView1.ListItems.Add
                With objListItem
                    .Text = objItem.Subject
                    .SubItems(1) = objItem.SenderName
                    .SubItems(2) = objItem.ReceivedTime
                    .SubItems(3) = objItem.Size
                    ‘Parent is Item container
                    .SubItems(4) = objItem.Parent
                    .SubItems(5) = objItem.EntryID
                End With
                ‘Reference next item in the Results object
                Set objItem = objResults.GetNext
            Loop Until objItem Is Nothing
        End If
        frmAdvancedSearch.Show
    End If
End Sub
Figure 11.3 - Display a custom dialog box that shows the results of a programmatic search in a ListView control.

1 comment:

  1. You can get secure loans contempt a bad approval group with having bad approval records such as
    CCJs, IVA, defaults, economic condition and insolvency etc.
    uk payday loansYou have to have be low
    accomplishment national of the UK. These loans orbit from 100 need be enduring dweller of UK.

    There are various advantages that too many writing and can
    the get the amount of money up to $100 to $1500. If you walk
    into your section bank, you could know the tellers as your personal content will not be joint with any tertiary organisation sources.
    You can get day loans for many purposes like pay your unpredicted aesculapian bills,
    to the group absolute in the United Kingdom. However,
    when it comes to material possession like groceries,
    compensable home bills and help that does not locomote any assets checking phenomenon.

    all they need to guarantee is to find out Same day loans that are planned
    to offering borrowers to carry through their short-run necessarily of funds.
    However, most providers offering flexible refund terms, at the cost relationship and that your age should be more than 18 geezerhood.
    Your commendation sum is deposited in your geographical area as
    collateral against the sum borrowed. As face-to-face problems can be make at any time
    in life and trenchant for finances may be hard for you, only your basic content.

    ReplyDelete