views:

33

answers:

0

I am writing an Outlook VBA macro to alphabetically sort recipients when composing an email.

It works fine for sorting, however if I have 3 recipients (for example), run the sort macro, and then remove a recipient, running the macro a second time causes the removed recipient to re-appear. When I step through the macro on the second run, I can see that both .CurrentItem.To and the Recipients object still have all 3 recipients.

It is sort of intermittent. Is there any way for me to force the Recipients object to update when the To: text box has been edited? I can't find anything in the Outlook VBA documentation and trial and error has proved fruitless.

Code excerpt:

Public Sub SortRecipients()
    With Application.ActiveInspector
        If TypeOf .CurrentItem Is Outlook.MailItem Then
            Debug.Print "Before: "
            Debug.Print "To: " & .CurrentItem.To
            Debug.Print "# of recipients: " & .CurrentItem.Recipients.Count

            ' Force an update if recipients have changed (DOESN'T HELP)
            .CurrentItem.Recipients.ResolveAll

            Set myRecipients = .CurrentItem.Recipients
            ' Create objects for To list
            Dim myRecipient As recipient
            Dim recipientToList As Object
            Set recipientToList = CreateObject("System.Collections.ArrayList")

            ' Create new lists from To line
            For Each myRecipient In myRecipients
                    recipientToList.Add myRecipient.Name
                End If
            Next

            ' Sort the recipient lists
            recipientToList.Sort
            ' Remove all recipients so we can re-add in the correct order
            While myRecipients.Count > 0
                myRecipients.Remove 1
            Wend

            ' Create new To line
            Dim recipientName As Variant
            For Each recipientName In recipientToList
                myRecipients.Add (recipientName)
            Next recipientName
            .CurrentItem.Recipients.ResolveAll

        End If
    End With
End Sub