【问题标题】:How to to populate the From, To, Cc of an email from a template?如何从模板填充电子邮件的发件人、收件人、抄送?
【发布时间】:2021-08-19 05:00:54
【问题描述】:

我在 Outlook 中使用 VBA 来调用电子邮件模板。我希望 VBA 填充 From、To、Cc 字段。

VBA 打开模板并创建新电子邮件,但发件人、收件人和抄送字段为空。

Sub Step_1()
    
    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(olMailItem)
    Set msg = Application.CreateItemFromTemplate("C:\Myfolder\Templates\Action Required documents needed.oft")
    
    With OutMail
        .SentOnBehalfOfName = "homebase@gmail.com"
        .To = "Jane.Doe@customer.com"
        .CC = "homebase@gmail.com"
        msg.Display
    End With
    On Error GoTo 0
    
    Set OutMail = Nothing
    Set OutApp = Nothing

End Sub

【问题讨论】:

  • With msg 不是With OutMail

标签: vba outlook


【解决方案1】:

按照我的理解,有两种做法:

  1. 使用 CreateItem 方法来创建默认项
  2. 使用 CreateItemFromTemplate 方法,以便您可以基于模板创建项目

让我们从第一种方法开始。语法如下:expression.CreateItem(ItemType),其中expression 返回Application 对象,ItemType 是必填参数(您可以选择:olContactItemolDistributionItemolMailItem 等)。所以你可以像这样创建一个新的电子邮件:

Sub email_option1()
Dim msg As MailItem
Set msg = Application.CreateItem(ItemType:=olMailItem)
With msg
  .To = 'recipient
  .CC = 'CCs
  .Subject = 'subject
  .Body = 'body of the email
  .Attachments.Add ("C:\Attachments\Test File.docx") 'if any attachments needed
  .Importance = olImportanceHigh 'if it is important
  .Display 'or .Send
End With
Set msg = Nothing
End Sub

或者您可以选择第二种方法,正如您提到的那样,您可能想要一个可以使用的模板。语法为:expression.CreateItemFromTemplate(TemplatePath, InFolder),其中表达式再次返回 Application 对象,TemplatePath 是必需的字符串参数,它告诉我们要使用的模板的位置。 InFolder 是我从不使用的可选参数(不完全确定它的作用)。所以你的代码可能是这样的:

Sub email_option2()
Dim msg As MailItem
Set msg = Application.CreateItemFromTemplate("C:\Myfolder\Templates\Action Required documents needed.oft")
With msg
  .To = "Jane.Doe@customer.com"
  .CC = "homebase@gmail.com"
  .Subject = 'subject
  .Display 'or .Send
End With
Set msg = Nothing
End Sub

至于.SentOnBehalfOfName = "homebase@gmail.com" 行。我不确定它是否符合您的要求。看这里:SentOnBehalfOfName Microsoft HelpIssue with SentOnBehalfOfNameMore on SentOfBehalfOfName。如果这是您想要实现的,那么您可以简单地将这一行放回代码中。

【讨论】:

    猜你喜欢
    • 2011-07-24
    • 2019-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-01
    • 1970-01-01
    • 2017-10-01
    • 1970-01-01
    • 2022-12-11
    相关资源
    最近更新 更多