简体   繁体   English

使用 Outlook 模板和设置变量从 Excel 2007 VBA 发送电子邮件

[英]Send an email from Excel 2007 VBA using an Outlook Template & Set Variables

I have a list of data, let's say client information (Name, Email, Amount Owing etc.), stored in an Excel worksheet.我有一个数据列表,比如说客户信息(姓名、电子邮件、欠款等),存储在 Excel 工作表中。 My aim is to click a button in Excel and send each client their information in an Outlook Template.我的目标是单击 Excel 中的一个按钮,并在 Outlook 模板中向每个客户发送他们的信息。

  1. create a mail object创建邮件对象
  2. set the mail object to the template file将邮件对象设置为模板文件
  3. setting and then filling in the template with data about the current client - mostly stuck here, not sure how to specify variables in a template and then relate to them in VBA设置然后用有关当前客户端的数据填充模板 - 主要停留在这里,不确定如何在模板中指定变量,然后在 VBA 中与它们相关联
  4. save to drafts for later review/send保存到草稿供以后查看/发送

eg Dear << clientname >> = Dear John Smith例如,亲爱的 << 客户名 >> = 亲爱的约翰·史密斯

My code thus far:到目前为止我的代码:

Dim myOlApp As Outlook.Application
Dim MyItem As Outlook.MailItem

Set myOlApp = CreateObject("Outlook.Application")
Set MyItem = myOlApp.CreateItemFromTemplate("C:\egTemplate.oft")

With MyItem
    .To = Worksheets("Clients").Range(1, 2)
    .Subject = "Monthly bill"
    'Refer to and fill in variable items in template
    .Save
End With

Set MyItem = Nothing
Set MyOlApp = Nothing

Here is what you can do :这是您可以执行的操作:

With MyItem
    'Refer to and fill in variable items in template
    .Body = Replace(.Body, "<< clientname >>", Worksheets("Clients").Range(1, 2))
End With

or, if your mail is in HTML:或者,如果您的邮件是 HTML:

With MyItem
    'Refer to and fill in variable items in template
    .HTMLBody = Replace(.HTMLBody, "&lt;&lt; clientname &gt;&gt;",  Worksheets("Clients").Range(1, 2))
End With

Tested successfully on Excel / Outlook 2007在 Excel / Outlook 2007 上测试成功

This is a perfect job for mail merge.这是邮件合并的完美工作。 If you want to do it programmatically, see如果您想以编程方式执行此操作,请参阅

Mail Merge in Word+Excel using VBA使用 VBA 在 Word+Excel 中合并邮件

Or you could simply do it manually (from Word), inserting merge fields and then selecting your workbook as the data source.或者您可以简单地手动(从 Word)执行此操作,插入合并字段,然后选择您的工作簿作为数据源。 You can merge to email and Outlook will send out personalized emails to each recipient's email using the information from each row/record.您可以合并到电子邮件,Outlook 将使用每行/记录中的信息向每个收件人的电子邮件发送个性化电子邮件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM