Share via


How to: Programmatically access Outlook contacts

Applies to: yesVisual Studio noVisual Studio for Mac

Note

This article applies to Visual Studio 2017. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

This example finds all contacts whose last names contain a specified search string.

Applies to: The information in this topic applies to VSTO Add-in projects for Outlook. For more information, see Features available by Office application and project type.

Example

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    AccessContacts("Na");
}

private void AccessContacts(string findLastName)
{
    Outlook.MAPIFolder folderContacts = this.Application.ActiveExplorer().Session.
        GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
    Outlook.Items searchFolder = folderContacts.Items;
    int counter = 0;
    foreach (Outlook.ContactItem foundContact in searchFolder)
    {
        if (foundContact.LastName.Contains(findLastName))
        {
            foundContact.Display(false);
            counter = counter + 1;
        }
    }
    MessageBox.Show("You have " + counter +
        " contacts with last names that contain "
        + findLastName + ".");
}
Private Sub ThisAddIn_Startup(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Startup
    AccessContacts("Na")
End Sub

Private Sub AccessContacts(ByVal findLastName As String)
    Dim folderContacts As Outlook.MAPIFolder = Me.Application.ActiveExplorer() _
        .Session.GetDefaultFolder(Outlook.OlDefaultFolders _
        .olFolderContacts)
    Dim searchFolder As Outlook.Items = folderContacts.Items
    Dim counter As Integer = 0
    For Each foundContact As Outlook.ContactItem In searchFolder
        If foundContact.LastName.Contains(findLastName) Then
            foundContact.Display(False)
            counter = counter + 1
        End If
    Next
    MsgBox("You have " & counter & _
        " contacts with last names that contain " _
        & findLastName & ".")
End Sub

Compile the code

This example requires:

  • Contacts whose last names contain the string "Na" (for example, Tzipi Butnaru) in the Contacts folder.

See also