目次
Environment
- OS: Windows 10 Pro
- Software: Microsoft Excel VBA, Outlook
Background
When creating Outlook emails using VBA, I used to write & vbCrLf repeatedly to insert line breaks in the body text. However, this made the code very difficult to read and look messy.
In this article, I will share a cleaner and more efficient way to write this code.
Solution: Construct the Body Using a For Loop
If you want to insert multiple lines into the email body, using a For loop to build the text makes the code much more organized.
Code Example (Adding content from cells D5 to D62 with line breaks)
Dim i As Long
For i = 5 To 62
objMail.Body = objMail.Body & Range("D" & i).Value & Chr(10)
Next i
Code Explanation
- Line 1: Declare the counter variable
ias aLongtype. - Line 3: Loop from row 5 to row 62, reading the cells in column D one by one.
- Line 4:
Range("D" & i).Valueretrieves the value of the target cell.Chr(10)inserts a line break code (LF: Line Feed).- The cell content and the line break are appended to the existing body (
objMail.Body).
Key Points
- Chr(10) represents a line break (LF) and works perfectly in Outlook email bodies.
- Using a
Forloop is much cleaner than writing& vbCrLf &repeatedly. It also improves maintainability. - This method offers flexibility; you can easily change the content of the email just by changing the range of cells being read.
Summary
If you want to create an Outlook email body with proper formatting:
- Use a For loop to read cell contents sequentially.
- Use Chr(10) to insert line breaks.
By using this method, you can write code that is “easy to read and easy to expand.” This also improves the quality of your email automation tools.
