通过使用换行符创建来自单元格值的消息,在电子邮件中添加新行:VBA

时间:2017-06-22 09:27:28

标签: excel vba excel-vba email

我正面临与VBA中的邮件相关的问题。

例如。在单元格A1中我有:

Test test test

test


test test

当我从单元格A1生成邮件时,字符串显示没有换行符,我的意思是

Test test test test test test. 

我尝试使用从"\r\n"替换为"<br/>",但这不起作用。

Content = Replace(Content , "\r\n", "<br/>")

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:3)

关键是用HTML换行符替换Excel的换行符Chr(10) <br>

电子邮件代码:

Sub mail()
    Dim OutApp As Object, OutMail As Object, strbody As String

    ' Get string from cell, replace Chr(10) (the cell new line) with a html <br>
    strbody = ThisWorkbook.Sheets("Sheet1").Range("A1").Value
    strbody = Replace(strbody, Chr(10), "<br>")

    ' Create email and add string as HTMLBODY item
    On Error Resume Next
    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)
    With OutMail
        .to = ""
        .CC = ""
        .Subject = "Subject here"
        .htmlbody = strbody
        .Display
    End With
    On Error GoTo 0
End Sub

输出继电器:

test