如何在 VBA 宏中添加换行符

如何在 VBA 宏中添加换行符

我是 VBA 宏的新手,需要有关以下代码的建议。

[Excel 单元格]

Sub Create_email()

Dim OutApp As Object
Dim OutMail As Object

Dim strName As String
Dim strTo As String
Dim strCc As String
Dim strBody As String

strName = Range("B1").Value
strTo = Range("B2").Value
strCc = Range("B3").Value

If strName <> "" Then
    e_msg = "Hello " & strName & vbCrLf & _
    "Welcome Back " & vbCrLf & _
    "Regards " & vbCrLf & _
    "Management "
    MsgBox (e_msg)
End If

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)
    ' Create Email subject
    strSubj = "Hello " & strName
    
    ' Create body of email
    *strBody = "<html> <body style=font-size:11pt;font-family:Arial>" & e_msg & "<br><br>" & _
    "Please let us know if there are any issues. <br><br>" & _
    "</body> </html>"*

    With OutMail
        .To = strTo
        .CC = strCc
        .BCC = ""
        .Subject = strSubj
        .htmlBody = strBody
        .Display  '.Send 'or use .Display
    End With

Set OutMail = Nothing
Set OutApp = Nothing

End Sub

我希望以这种格式创建电子邮件

Hello John

Welcome Back Regards Management

Please let us know if there are any issues.

但代码没有在电子邮件正文中的 John 和 Welcome 之间添加新行

Hello John Welcome Back Regards Management 
Please let us know if there are any issues.

答案1

看起来vbCrLf字符串中的 不会在 HTML 主体中显示为换行符。有以下几种解决方法:

  1. 将它们替换e_msg<br><br>

    e_msg = "Hello " & strName & "<br><br>Welcome Back<br><br>Regards<br><br>Management"

  2. e_msg事后更换它们:

    e_msg = Replace(e_msg, vbCrLf, "<br><br>")

相关内容