3
votes

I have a list of first and last names in Excel and I want to utilize that list to look up email address in Outlook using visual basic.

I'm using the following VB code:

    Private Sub GetAddresses()
    Dim o, AddressList, AddressEntry
    Dim c As Range, r As Range, AddressName As String
    Set o = CreateObject("Outlook.Application")
    Set AddressList = o.Session.AddressLists("Global Address List")
    Set r = Range("a1:a3")
    For Each c In r
        AddressName = Trim(c.Value) & ", " & Trim(c.Offset(0, 1).Value)
        For Each AddressEntry In AddressList.AddressEntries
            If AddressEntry.Name = AddressName Then
                c.Offset(0, 2).Value = AddressEntry.Address
                Exit For
            End If
        Next AddressEntry
    Next c
    End Sub

The code seems to be working fine up until the point of actually retrieving the email address. After it matches a name its returning the following instead of the address. Does anyone have an idea of what I'm doing wrong.

/O=Compnay/OU=Company/cn=Recipients/cn=shs

Thanks in advance for you help.

2
can you please show a sample of your data - frist name, last name ?userAZLogicApps

2 Answers

6
votes

I am assuming that these are domain users. You want to get the SMTP address from the exchangeUser object. I have updated your code to show this.

Private Sub GetAddresses()
    Dim o, AddressList, AddressEntry
    Dim c As Range, r As Range, AddressName As String
    'added variable for exchange user object
    Dim exchangeUser As Outlook.exchangeUser

    Set o = CreateObject("Outlook.Application")
    Set AddressList = o.Session.AddressLists("Global Address List")
    Set r = Range("a1:a3")
    For Each c In r
        AddressName = Trim(c.Value) ' & ", " & Trim(c.Offset(0, 1).Value)
        For Each AddressEntry In AddressList.AddressEntries
            If AddressEntry.Name = AddressName Then
            'set the exchange user object
            Set exchangeUser = AddressEntry.GetExchangeUser
            'get the smtp addresss
            c.Offset(0, 2).Value = exchangeUser.PrimarySmtpAddress
            'release
            Set exchangeUser = Nothing
                Exit For
            End If
        Next AddressEntry
    Next c
End Sub
0
votes

Ouch! Why would you want to loop through all items in an address list that can potentially contains tens of throusands of entries? Use Aplication.Sesssion.CreateRecipient, then call Recipient.Resolve. If successful, you can retrieve the AddressEntry object from Recipient.AddressEntry.
If you need to make sure the name is resolved against GAL only (by the way, you should not hardcode the GAL name, it will differ based on locale), you can use Redemption and its AddreessList.ResolveName method - all you need to do is call RDOSession.AddressBook.GAL.ResolveName