Whats wrong with the macro for Outlook App from excell sheet?
I am trying to fetch all the user email addresses from outlook.
In the sheet I have a list of names of the user.
VBA macro version for Excel to read names from column D, search the Outlook Address Book (GAL and Contacts), and fill email addresses in column E. This uses late binding—no need to set VBA references.
what is late binding when it comes to vba and outlook?
does it really matter?
Sub LookupOutlookEmails()
Dim olApp As Object
Dim olNS As Object
Dim olRecipient As Object
Dim olExUser As Object
Dim ws As Worksheet
Dim lastRow As Long
Dim i As Long
Dim name As String
Dim email As String
' Use the active worksheet
Set ws = ActiveSheet
lastRow = ws.Cells(ws.Rows.Count, "D").End(xlUp).Row
' Connect to Outlook
On Error Resume Next
Set olApp = GetObject(, "Outlook.Application")
If olApp Is Nothing Then
Set olApp = CreateObject("Outlook.Application")
End If
On Error GoTo 0
If olApp Is Nothing Then
MsgBox "Outlook is not running or not installed.", vbCritical
Exit Sub
End If
Set olNS = olApp.GetNamespace("MAPI")
Application.ScreenUpdating = False
For i = 2 To lastRow
name = Trim(ws.Cells(i, "D").Value)
email = ""
If Len(name) > 0 Then
Set olRecipient = olNS.CreateRecipient(name)
olRecipient.Resolve
If olRecipient.Resolved Then
On Error Resume Next
Set olExUser = olRecipient.AddressEntry.GetExchangeUser
If Not olExUser Is Nothing Then
email = olExUser.PrimarySmtpAddress
Else
' Use Address property for contacts (may return Exchange X500 if not SMTP)
email = olRecipient.AddressEntry.Address
End If
On Error GoTo 0
Else
email = "NOT FOUND"
End If
End If
ws.Cells(i, "E").Value = email
Next i
Application.ScreenUpdating = True
MsgBox "Email lookup complete!", vbInformation
End Sub