Paste this code into one of your VBA Project modules in Excel, and run the
GetNamesFromGALUsingAlias macro after selecting the aliases in the
spreadsheet. Note that you must have Collaboration Data Objects installed;
you can do that through Office Setup - check the Outlook components for the
CDO entry. CDO is required - you cannot access first name and last name
values from AddressEntry objects with Outlook VBA
The code will enter the first name and last name values into two columns to
the right of the column with the aliases.
Option Explicit
Const CdoPR_GIVEN_NAME = &H3A06001E 'First (name)
Const CdoPR_SURNAME = &H3A11001E 'Last (name)
Sub GetNamesFromGALUsingAlias()
On Error Resume Next
Dim objSession As Object
Dim objAddList As Object
Dim objAddresses As Object, objAddress As Object
Dim objFields As Object, objField As Object
Dim strLastName As String, strFirstName As String
Dim objRange As Excel.Range, varValues() As Variant, intX As Integer,
strAlias As String
Set objRange = Selection
If objRange Is Nothing Then
MsgBox "Nothing is selected!"
Exit Sub
End If
varValues = objRange.Value2
Set objSession = CreateObject("MAPI.Session")
If Err.Number <> 0 then
MsgBox("CDO is not installed!")
Exit Sub
End If
objSession.Logon , , True, True
Set objAddList = objSession.AddressLists("Global Address List")
Set objAddresses = objAddList.AddressEntries
'LOOP THROUGH SELECTED CELLS TO GET THE ALIAS
For intX = LBound(varValues, 1) To UBound(varValues, 1)
strAlias = varValues(intX, 1)
For Each objAddress In objAddresses
If objAddress.Name = strAlias Then
Set objFields = objAddress.Fields
Set objField = objFields.Item(CdoPR_SURNAME)
If Not objField Is Nothing Then
strLastName = objField.Value
End If
Set objField = objFields.Item(CdoPR_GIVEN_NAME)
If Not objField Is Nothing Then
strFirstName = objField.Value
End If
'WRITE FIRST AND LAST NAME TO ADJACENT COLUMNS
Cells(intX, objRange.Column + 1).Value = strFirstName
Cells(intX, objRange.Column + 2).Value = strLastName
Exit For
End If
Next
Next
objSession.Logoff
Set objAddList = Nothing
Set objAddresses = Nothing
Set objAddress = Nothing
Set objSession = Nothing
Set objFields = Nothing
Set objField = Nothing
End Sub