我正在尝试在VBA中实现一个代码,该代码将根据3种不同的条件将电子邮件发送给不同的收件人。如果满足条件1,则将电子邮件发送到email01;如果满足条件2,则将CC发送到email02;如果满足条件2,则将电子邮件发送到email03和CC email04等。因此,实质上,唯一会改变的是是。到&.CC取决于代码中是否存在条件。
到目前为止,我已经在VBA中创建了处理以下Outlook应用程序的电子邮件模板。
Sub CreatingEmailTemplate()
Dim OutApp As Object
Dim OutMail As Object
Dim strbody As String
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
strbody = "Sample Text" & "<br><br>" & _
"Sample TextSample TextSample TextSample TextSample TextSample TextSample Text" & "<br><br>" & _
"Sample TextSample Text" & "<br><br><br>" & _
"Sample TextSample TextSample TextSample" & "<br>" & _
"Sample Text" & "<br>" & _
"Sample Text" & "<br>" & _
"Sample TextSample TextSample TextSample TextSample Text" & "<br>" & _
"Sample Text" & "<br>" & _
"Sample Text " & "<br>" & _
"Sample TextSample Text" & "<br><br><br>" & _
"<b>Sample TextSample TextSample TextSample TextSample Text" & "<br>" & _
"Sample TextSample TextSample TextSample TextSample TextSample Text<b>"
On Error Resume Next
'Trying to implement a variable condition. depending on what condition is met the recipient of sending emails (To & CC) would change
With OutMail
.To = "SampleEmail01@abc.com"
.CC = "SampleEmail02@abc.com"
.BCC = ""
.Subject = "Sending email to different recipients"
.htmlBody = strbody
'You can add a file like this
'.Attachments.Add ("C:\test.txt")
'OutMail.Display True
.Display 'or use .Send to send automatically
End With
On Error GoTo 0
'MsgBox "Email Send"
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
一切正常,我想我可以使用3个不同的模块来处理3个不同的条件,但我希望可以将所有内容组合在一个代码中。有任何想法吗?
答案 0 :(得分:0)
您可以通过变量设置to和cc,然后像这样调用整个方法
Sub CreatingEmailTemplate(to_recipients as String, cc_recipients as string)
...
With OutMail
.To = to_recipients
.CC = cc_recipients
.BCC = ""
.Subject = "Sending email to different recipients"
.htmlBody = strbody
'You can add a file like this
'.Attachments.Add ("C:\test.txt")
'OutMail.Display True
.Display 'or use .Send to send automatically
End With
或
Sub CreatingEmailTemplate()
dim to_recipients as String
dim cc_recipients as string
if (condition1=true) then
to_recipients = "email01"
cc_recipients = "email02"
elseif (condition2=true) then
to_recipients = "email03"
cc_recipients = "email04"
elseif (condition3=true) then
to_recipients = "email01"
cc_recipients = "email04"
else
end if
...
With OutMail
.To = to_recipients
.CC = cc_recipients
.BCC = ""
.Subject = "Sending email to different recipients"
.htmlBody = strbody
'You can add a file like this
'.Attachments.Add ("C:\test.txt")
'OutMail.Display True
.Display 'or use .Send to send automatically
End With