VBA使用CDO发送带格式的电子邮件

时间:2014-05-08 13:16:03

标签: excel excel-vba vba

我有这个代码,有效。

  Private Sub CommandButton1_Click()
  Dim Mail As New Message
  Dim Config As Configuration
  Set Config = Mail.Configuration
  Dim cell As Range
  Dim strbody As String
  For Each cell In Sheets("Sheet1").Range("C2:D9")
      strbody = strbody & cell.Value & vbNewLine
  Next

  Config(cdoSendUsingMethod) = cdoSendUsingPort
  Config(cdoSMTPServer) = "smtp.gmail.com"
  Config(cdoSMTPServerPort) = 25
  Config(cdoSMTPAuthenticate) = cdoBasic
  Config(cdoSMTPUseSSL) = True
  Config(cdoSendUserName) = "MyEmail"
  Config(cdoSendPassword) = "EmailPassword"
  Config.Fields.Update

  Mail.To = Sheets("Sheet1").Range("j2").Value
  Mail.From = Config(cdoSendUserName)
  Mail.Subject = "Email Subject"
  Mail.TextBody = strbody

  If G9 = "Yes" Then
  Mail.AddAttachment "C:\...file1.xls"
  Mail.AddAttachment "C:\...file2.xls"
  End If

  On Error Resume Next

  Mail.Send

  If Err.Number <> 0 Then
    MsgBox Err.Description, vbCritical, "There was an error"
    Exit Sub
  End If
  MsgBox "Your email has been send!", vbInformation, "Sent"

End Sub

它将采用我在C2中的文字:D9,但它不会像在工作表中那样对其进行格式化,因此它在发送时看起来像这样: 项目1
结果1
项目2
结果2
项目3
Result3
项目4
Result4

如果我将Mail.TextBody设置为Mail.HTMLBody,它就会出现如下:

Item1 Result1 Item2 Result2 Item3 Result3 Item4 Result4

如何在excel表格中格式化它,确切地发送那些范围内的内容? 如果我手动复制这些单元格并将它们粘贴到电子邮件正文中,它将保留单元格结构,字体大小,字体颜色和任何背景颜色。

第1项结果1 第2项结果2 项目3结果3
第4项结果4

我一直在网上寻找很多尝试找到这个但却无法获得CDO。我找到了Outlook的一些项目,但我没有使用Outlook。

是否可以使用发送电子邮件的CDO电子邮件方法发​​送格式化的单元格块?

谢谢。

1 个答案:

答案 0 :(得分:1)

使用HTML格式的邮件的示例如下。您需要包含正确的标记:

Set OutApp = New Outlook.Application
Set OutMail = OutApp.CreateItem(olMailItem)

With OutMail

    fEmailTOSend = RepEmailTO


    .To = "me@me.co.uk"
    .Subject = "report created " & strdate
    .BodyFormat = 2 '<<HTML
    .importance = 2 '<<High
    .HTMLBody = "<P>" & _
        "<BR>" & _
        "<FONT face=""Lucida Sans Unicode"" size=2.5>" & _
               myEmailNarrative & _
               "<BR>" & _
               "Kind Regards," & _
               "<BR>" & _
               "<FONT color=#0000ff>" & _
                           ProfileName & "." & _
               "</FONT>" & _
        "</FONT>" & _
        "</P>" & _
    "</BODY></HTML>"
    .Attachments.Add wb.FullName
    .Save
    .Send
End With