我目前正在开发一个访问Vba程序,以便自动向人们发送邮件。但是我们选择仍然手动在Outlook中按“发送”(如果可能存在问题,我们可以事先控制邮件)。
是否有办法在另一个方向上建立链接,例如,当按下Outlook中的“发送”按钮时,在Excel中获取该人员的电子邮件地址? (目标是制作一份“历史”表,以便跟踪实际发送的邮件和邮件)
谢谢!
答案 0 :(得分:1)
是。一个简单的案例如下所示。这很简单,展示了您所要求的行动。
公共变量addressSent
包含To地址。对已发送的邮件项目(由@Rory)进行测试的布尔测试,由@Dwipayan Das调用函数,打开指定的Excel文件,并将addressSent
写入sheet1中的单元格A1。
你可以修改它以适合你的目的。例如。调整函数以接受文件名作为参数.....
记下来自@ ashleedawg的书:记得包含一个xlApp.Quit行,这样就不会留下Excel。
我相信您的问题想要从Outlook转到Excel,因此这是您创建的需要关闭的应用程序。
所以在Outlook中会出现以下代码:
将其放入标准模块中:
Option Explicit
Public addressSent As String
Dim itmevt As New CMailItemEvents
Public Sub CreateNewMessage()
Dim objMsg As MailItem
Set objMsg = Application.CreateItem(olMailItem)
Set itmevt.itm = objMsg
With objMsg
.Display
.To = "somebody@mail.com"
.Subject = "Blah"
addressSent = .To
.Send
End With
End Sub
Public Function openExcel() As Boolean 'Adapted from @Dwipayan Das
Dim xlApp As Object
Dim sourceWB As Object
Dim sourceWS As Object
Set xlApp = CreateObject("Excel.Application")
With xlApp
.Visible = True
.EnableEvents = False
End With
Dim strFile As String
strFile = "C:\Users\User\Desktop\Delete.xlsb" 'Put your file path.
Set sourceWB = xlApp.Workbooks.Open(strFile, , False, , , , , , , True)
sourceWB.Activate
sourceWB.Worksheets(1).Range("A1") = addressSent
End Function
然后在名为CMailItemEvents
的类模块中,来自@Rory的代码,提出以下内容:
Option Explicit
Public WithEvents itm As Outlook.MailItem
Private Sub itm_Close(Cancel As Boolean)
Dim blnSent As Boolean
On Error Resume Next
blnSent = itm.Sent
If Err.Number = 0 Then
Debug.Print "not sent"
Else
openExcel
End If
End Sub
参考文献:
答案 1 :(得分:0)
只是一个快速的脏函数,它将在Excel / Access / Word中运行,并返回Sent Items
文件夹中最新项目的电子邮件地址(无错误处理等):
Function LastSentEmailAddress() As String
'Requires reference: "Microsoft Outlook xx.x Object Library"
Dim olApp As Outlook.Application, olMail As Object
Set olApp = New Outlook.Application 'create Outlook object
Set olMail = olApp.GetNamespace("MAPI").GetDefaultFolder(olFolderSentMail).Items.GetLast
LastSentEmailAddress = olMail.Recipients(1).PropertyAccessor.GetProperty( _
"http://schemas.microsoft.com/mapi/proptag/0x39FE001E") 'get email addy
olApp.Quit 'close Outlook
End Function
关于使用Excel中的Outlook对象的注意事项:
使用Excel等应用程序时,确保应用程序对象在完成后.Quit
/ .Close
'是正确的,并且Set
所有对象都{ {1}}),否则存在无意中运行多个实例的风险,这可能导致内存泄漏,从而导致崩溃和潜在的数据丢失。
要检查是否存在Outlook的现有实例,请使用此功能:
Nothing
(来源: https://jsfiddle.net/RACCH/puhyo7oa/ )
MSDN:Rob de Bruin
Office.com:Obtain the E-mail Address of a Recipient
MSDN:How to disable warnings about programmatic access to Outlook(图书摘录)
Stack Overflow:Check or Add an Object Library Reference