使用VBA

时间:2016-07-25 20:08:10

标签: vba outlook

我有一个名为selectRec的按钮,用户可以点击用户窗体。

我希望单击该按钮,然后他们的Outlook通讯录对话框会提示他们添加收件人。然后,收件人将被添加到ListBox1。下面的代码只允许添加一个收件人,即使选择了许多收件人。这是因为它只访问oDialog.recipients.Item数组中的第一项。我不知道如何使用for循环迭代我不知道长度的东西(因为他们可以添加尽可能多的电子邮件地址)

  Private Sub selectRec_Click()

    Dim olApp As Outlook.Application
    Dim oDialog As SelectNamesDialog
    Dim oGAL As AddressList
    Dim myAddrEntry As AddressEntry
    Dim exchUser As Outlook.ExchangeUser

    Dim AliasName As String
    Dim FirstName As String
    Dim LastName As String
    Dim EmailAddress As String

    Set olApp = GetObject(, "Outlook.Application")
    Set oDialog = olApp.Session.GetSelectNamesDialog
    Set oGAL = olApp.GetNamespace("MAPI").AddressLists("Global Address List")

    With oDialog
        .AllowMultipleSelection = True
        .InitialAddressList = oGAL
        .ShowOnlyInitialAddressList = True



        If .Display Then

          AliasName = oDialog.recipients.Item(1).Name

            Set myAddrEntry = oGAL.AddressEntries(AliasName)
            Set exchUser = myAddrEntry.GetExchangeUser

            If Not exchUser Is Nothing Then
                FirstName = exchUser.FirstName
                LastName = exchUser.LastName
                EmailAddress = exchUser.PrimarySmtpAddress

            End If
            ListBox1.AddItem (EmailAddress)



        End If
    End With
Set olApp = Nothing
Set oDialog = Nothing
Set oGAL = Nothing
Set myAddrEntry = Nothing
Set exchUser = Nothing
End Sub

1 个答案:

答案 0 :(得分:0)

你只需要为每个循环使用a并遍历每个Recipient

    If .Display Then

    Dim userSelected As Outlook.Recipient
        For Each userSelected In .Recipients

            AliasName = userSelected.Name

            Set myAddrEntry = oGAL.AddressEntries(AliasName)
            Set exchUser = myAddrEntry.GetExchangeUser

            If Not exchUser Is Nothing Then
                FirstName = exchUser.FirstName
                LastName = exchUser.LastName
                EmailAddress = exchUser.PrimarySmtpAddress

            End If
            ListBox1.AddItem (EmailAddress)

        Next
    End If