VBA outlook - retrieve email address from excel as recipient

和自甴很熟 提交于 2019-12-12 01:47:12

问题


I would like to retrieve the email addresses from excel cells and copy them as recipients on outlook.

However, the "To" and "CC" on outlook are empty.

input and output:

Cell A1 is the email address which I want to "send to".

Cell A2 is the email address which I want to "CC to".

my VBA code:

Sub Button1_Click()

    Dim OutApp As Object
    Dim OutMail As Object




    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(olMailItem)



    On Error Resume Next
    With OutMail
        .To = Cells("A1")
        .CC = Cells("A2")
        .BCC = ""
        .Subject = "This is the Subject line"

    End With
    On Error GoTo 0


    Set OutMail = Nothing
    Set OutApp = Nothing

End Sub

回答1:


You need to add a recipient, not the To, CC or BCC properties. These properties contain the display names only. The Recipients collection should be used to modify this property. For example:

Sub CreateStatusReportToBoss()  
   Dim myItem As Outlook.MailItem  
   Dim myRecipient As Outlook.Recipient 
   Set myItem = Application.CreateItem(olMailItem)  
   Set myRecipient = myItem.Recipients.Add("Dan Wilson")  
   myItem.Subject = "Status Report"  
   myItem.Display  
End Sub

You may find the following articles helpful:

  • How To: Create and send an Outlook message programmatically
  • How To: Fill TO,CC and BCC fields in Outlook programmatically



回答2:


If you remove "On Error Resume Next" you can debug. The following are invalid:

.To = Cells("A1")
.CC = Cells("A2")

Try

.To = Range("A1")
.CC = Range("A2")



回答3:


I have had better luck with a Recipient:

'If not defined:
'olBCC=3
'olCC=2
'olTo=1

Set OutMail = Application.CreateItem(olMailItem) 
Set myRecipient = OutMail.Recipients.Add(Range("A1"))
'myRecipient.Type = olTo
'This is default - use for clarity if desired
Set myRecipient = OutMail.Recipients.Add(Range("A2")) 
myRecipient.Type = olCC

If you wish to add multiple recipients, you will have to add them one at a time



来源:https://stackoverflow.com/questions/28090655/vba-outlook-retrieve-email-address-from-excel-as-recipient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!