2020-09-17

从Excel中读取邮件地址,通过Outlook Exchange查询姓名和部门,并写回表格。

Sub Run()
Dim emailAddr As String
Dim cell As Range
Dim myXL As Excel.Application
Dim wb As Excel.workbook

Dim colAL As Outlook.AddressLists
Dim oAL As Outlook.AddressList
Dim colAE As Outlook.AddressEntries
Dim oAE As Outlook.AddressEntry
Dim oExUser As Outlook.ExchangeUser

Set colAL = Application.Session.AddressLists


Dim MyExcelPath As String
MyExcelPath = "C:\Users\li_leibj\Desktop\123.xlsx"
Dim myExcelName As String
myExcelName = "123.xlsx"

Set myXL = CreateObject("Excel.Application")
Set wb = myXL.Workbooks.Open(FileName:=MyExcelPath) ', ReadOnly:=False)
myXL.Visible = True
myXL.Windows(myExcelName).Activate
wb.Activate
wb.Worksheets("Sheet2").Activate
wb.Worksheets("Sheet2").Visible = True

wb.Worksheets("Sheet2").Cells(1, 7) = "Name"
wb.Worksheets("Sheet2").Cells(1, 8) = "Department"

For Each cell In wb.Worksheets("Sheet2").Range("F2:F199")
    'Pre-Set to INVALID
    wb.Worksheets("Sheet2").Cells(cell.Row, cell.Column + 1) = "INVALID"
    wb.Worksheets("Sheet2").Cells(cell.Row, cell.Column + 2) = "INVALID"
    emailAddr = cell.Value
    For Each oAL In colAL
       'Address list is an Exchange Global Address List
       If oAL.AddressListType = olExchangeGlobalAddressList Then
           Set colAE = oAL.AddressEntries
           For Each oAE In colAE
               If oAE.AddressEntryUserType = olExchangeUserAddressEntry _
                  Or oAE.AddressEntryUserType = olExchangeRemoteUserAddressEntry Then
                  Set oExUser = oAE.GetExchangeUser
                  Debug.Print (oExUser.Name)
                  If oExUser.PrimarySmtpAddress = emailAddr Then
                      wb.Worksheets("Sheet2").Cells(cell.Row, cell.Column + 1) = oExUser.Name
                      wb.Worksheets("Sheet2").Cells(cell.Row, cell.Column + 2) = oExUser.Department
                      Debug.Print (oExUser.Name)
                      Debug.Print (oExUser.Department)
                      Exit For
                  End If
               End If
           Next
       End If
    Next
Next cell

myXL.Workbooks("123.xlsx").Close SaveChanges:=True

End Sub
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值