Outlook VBA生成HTML格式邮件时换行失效及编译错误问题求助
Fixing Outlook Email Line Breaks in VBA
Hey there, let's troubleshoot why your line breaks aren't working and fix those compilation errors with HTML tags!
The Root of the Problem
When you set .HTMLBody for an Outlook email:
vbCrLfis a plain-text line break — HTML ignores these, so they won't show up in the rendered email.- Your earlier attempts with
<br>or<p>probably failed due to syntax issues in how you embedded them into the string, plus some messy HTML structure mistakes. - Mixing
+and&for string concatenation can also cause unexpected errors (stick with&for VBA string concatenation to avoid type mismatch issues).
Corrected Code
Here's the fixed version with proper HTML formatting and no compilation errors:
Dim strbody As String Set xOutlookObj = CreateObject("Outlook.Application") Set xEmailObj = xOutlookObj.CreateItem(0) With xEmailObj .Display .To = xMemberName5 .CC = "" .Subject = "Annual Review " & xMemberName & " Cust " & xMemberName3 ' Build proper HTML body with <br> for line breaks and <p> for paragraphs strbody = "<p style='font-family:calibri;font-size:11pt;color:rgb(31,78,121)'>" & xMemberName7 & ",</p>" _ & "<br>" _ & "<p style='font-family:calibri;font-size:11pt;color:rgb(31,78,121)'>Our records indicate that " & xMemberName & " is due for an annual pricing review. We are seeking an overall impact of " & xMemberName6 & "% increase to the rates. Updated Tariff page is attached.</p>" _ & "<br>" _ & "<p style='font-family:calibri;font-size:11pt;color:rgb(31,78,121)'>If there are any pricing issues which need to be addressed, please get back to me no later than " & Format(Date + 7, "mm/dd/yyyy") & ".</p>" _ & "<br>" _ & "<p style='font-family:calibri;font-size:11pt;color:rgb(31,78,121)'>Otherwise, the attached new pricing will be effective " & xMemberName4 & ". I encourage you to visit with your customer and deliver the new pricing ASAP.</p>" ' Replace default HTML body with our custom structured content .HTMLBody = strbody End With
Key Changes Made:
- Replaced
vbCrLfwith<br>(for line breaks) and wrapped each block of text in<p>tags to maintain clean HTML structure. - Switched to using
&exclusively for string concatenation (safer than+in VBA, especially when working with mixed data types like dates). - Formatted the date with
Format(Date + 7, "mm/dd/yyyy")to convert it to a string that displays correctly in HTML. - Removed the problematic
.HTMLBody & "</body>"snippet — when you call.Display, Outlook generates a full HTML document, so replacing.HTMLBodywith your properly structured content avoids nested<body>tags and formatting conflicts.
Bonus Tip
If you want to keep Outlook's default signature in the email, insert your custom HTML before the existing .HTMLBody instead of replacing it entirely:
.HTMLBody = strbody & .HTMLBody
内容的提问来源于stack exchange,提问作者MisterBeans
相关产品推荐
相关产品推荐

