Finance

Charts

Statistics

Macros

Search

Accessing Contacts in Outlook with Excel VBA

The following example lists all contacts whose last name begins with the letter « M »:

Sub AccessContacts()
    Dim appOutlook As Outlook.Application
    Dim ns As Outlook.Namespace
    Dim contactsFolder As Outlook.Folder
    Dim contact As Outlook.ContactItem
    Dim output As String
    ' Start Outlook application
    Set appOutlook = CreateObject("Outlook.Application")
    ' Get the MAPI namespace
    Set ns = appOutlook.GetNamespace("MAPI")
    ' Access the default Contacts folder
    Set contactsFolder = ns.GetDefaultFolder(olFolderContacts)
    ' Attempt to retrieve matching contacts
    On Error GoTo ErrorHandler
    For Each contact In contactsFolder.Items
        If Left(contact.LastName, 1) = "M" Then
            output = output & contact.LastName & ", " & contact.FirstName & _
                     " (" & contact.Email1Address & ")" & vbCrLf
        End If
    Next contact
    ' Display the collected contacts
    MsgBox output
    ' Clean up
    appOutlook.Quit
    Set contact = Nothing
    Set contactsFolder = Nothing
    Set ns = Nothing
    Set appOutlook = Nothing
    Exit Sub
ErrorHandler:
    ' Ignore errors and continue with next contact
    Resume Next
End Sub

Explanation:
This code accesses the default Contacts folder in Outlook, identified by the constant olFolderContacts.

All items in this folder are of the type ContactItem and possess properties such as last name (LastName), first name (FirstName), and primary email address (Email1Address).

The script examines the last name of each contact using the Left() function to check if the first character is « M ». For all contacts matching this criterion, it concatenates their last name, first name, and email address into a string.

If an error occurs while accessing any contact (for example, due to an unexpected item type), the error handler ensures the loop continues with the next contact, effectively ignoring problematic entries.

Finally, the compiled list of matching contacts is displayed in a message box.

0 0 votes
Évaluation de l'article
S’abonner
Notification pour
guest
0 Commentaires
Le plus ancien
Le plus récent Le plus populaire
Online comments
Show all comments
Facebook
Twitter
LinkedIn
WhatsApp
Email
Print
0
We’d love to hear your thoughts — please leave a commentx