[VBA] How to Add Line Breaks to Outlook Emails Cleanly (Loop Method)

目次

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

  1. Line 1: Declare the counter variable i as a Long type.
  2. Line 3: Loop from row 5 to row 62, reading the cells in column D one by one.
  3. Line 4:
    • Range("D" & i).Value retrieves 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 For loop 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:

  1. Use a For loop to read cell contents sequentially.
  2. 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.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次