首页 > 解决方案 > 通过用户表单从 Outlook 中检索电子邮件地址

问题描述

我想问一下是否有办法从用户表单文本框中输入的值从 Outlook 通讯簿中检索电子邮件地址并检索它。

例如,我的 textbox1 让用户输入他们想要搜索的人的全名,并使用搜索按钮,textbox2 将根据 textbox1 从 Outlook 通讯录中检索所有电子邮件地址。

目前我所拥有的是一个模块调用检索电子邮件

 Option Explicit
Sub GetAddresses()
    Dim o, AddressList, AddressEntry
    Dim c As Range, r As Range, AddressName As String
    Set o = CreateObject("Outlook.Application")
    Set AddressList = o.Session.AddressLists("Contacts")
    'Chage this range to include the first names only. AddressName assignment line handles concatenating the last name.
    Set r = Add.Emailname
    For Each c In r
        AddressName = c.Value & " " & c.Offset(0, 1).Value
        For Each AddressEntry In AddressList.AddressEntries
            If AddressEntry.name = AddressName Then
                c.Offset(0, 2).Value = AddressEntry.Address
                Exit For
            End If
        Next AddressEntry
    Next c
End Sub

在我的用户表单中,搜索按钮

Private Sub Searchbutton_Click()
Call GetAddresses
End Sub

代码是我从网上看到的。谁能帮我编辑和指导我?

标签: excelvbaoutlook

解决方案


我看到你已经复制了你的代码。此代码旨在循环一个范围。您可以简单地删除循环并实现您的文本框值并将其分配给您的搜索按钮。但是,您需要一个.ListBox1(而不是.TextBox2),因为您希望所有联系中的点击都出现在列表中。我还实现了.Instr查看搜索值是否出现在联系人名称中的功能(LCase确定使用)。这将使搜索姓氏的方式更容易。然后代码将如下所示:

Option Explicit
Private Sub GetAddresses()
Dim o, AddressList, AddressEntry
Dim AddressName As String
Set o = CreateObject("Outlook.Application")
Set AddressList = o.Session.AddressLists("Contacts")
 'Change this range accordingly
AddressName = UserForm1.TextBox1.Value
For Each AddressEntry In AddressList.AddressEntries
    If InStr(1, LCase(AddressEntry.Name), LCase(AddressName)) <> 0 Then
        UserForm1.ListBox1.AddItem AddressEntry.Address
    End If
Next AddressEntry
End Sub

Private Sub Searchbutton_Click()
UserForm1.ListBox1.Clear
Call GetAddresses
End Sub

推荐阅读