PDA

View Full Version : Solved: Building Distribution Lists Under VBA Control



MWE
01-07-2010, 08:02 PM
I am running Outlook 2003. I am trying to build some dist lists under VBA control. Since the contacts to be included in a given dist list could be accumulated in a variety of ways, I have written a general dist list building procedure that assumes an array of items for the dist list called olCandidates. The relevant code for the dist list building portion is shown below:
Dim DLName As String
Dim I As Long
Dim HowAdded As String
Dim Num As Long
Dim olDistList As Outlook.DistListItem
Dim olRcpnt As Outlook.Recipient

HowAdded = "name"
Num = UBound(olCandidates)

DLName = InputBox( _
"# contacts in this dist list:" & vbTab & Num & vbCrLf & _
"DistList Name?", "Build Dist List Utility")
If DLName = "" Then GoTo CleanUp

Set olDistList = Application.CreateItem(olDistributionListItem)
olDistList.DLName = DLName

For I = 1 To Num
Select Case HowAdded
Case Is = "emailaddress"
Set olRcpnt = Application.Session.CreateRecipient(olCandidates(I).EmailAddress)
Case Is = "name"
Set olRcpnt = Application.Session.CreateRecipient(olCandidates(I).Name)
End Select
olRcpnt.Resolve
If olRcpnt.Resolved Then
olDistList.AddMember olRcpnt
Else
MsgBox "could not resolve " & olRcpnt.Name
End If
Next I

olDistList.Save
MsgBox "dist list " & olDistList.DLName & " built and saved"

CleanUp:
Set olDistList = Nothing
Set olRcpnt = Nothing

End Sub The variable HowAdded controls what data is used to create a recipient:
If I use the contact's email address when creating the recipient, all recipients are resolved but the resulting distlist has used the email address for both the Name and the Email Address. That is not a show stopper, but I would like to fix it.
If I use the contact's name (I am using Contact.FullName), the resulting dist list has the Name and Email Address fields correct, but many of the candidate contacts are not resolved. I carefully checked the candidates that are not resolved and there are no "conflicts", e.g., two contacts with the same name.What am I doing wrong?

MWE
01-08-2010, 09:46 AM
I figured out what was wrong. Once I changed the string stored in olCondidates(i).Name from Contact.FullName to Contact.EmailXDisplayName, everything works fine. The key was reading the VBA Help stuff on CreateRecipient more carefully.