5 Ways of Adding New Line in VBA (Carriage Return)

In VBA, a newline can be added by using following: vbNewLine constant vbCrLf constant vbCr constant

This tutorial explains how to add new line in VBA in different ways

Adding a new line in VBA

In VBA, a newline can be added by using the following:

  • vbNewLine constant
  • vbCrLf constant
  • vbCr constant
  • vbLf constant
  • char(10) character

Let us see examples of these in the section below.

An example of vbNewLine constant for adding a new line

We have two string-type variables and assign both texts after declaration.

In a MsgBox, we will concatenate both strings and add a new line by the vbNewLine constant.

See the code and output below:

The code:

Sub newline_ex()

 Dim Str1 As String, Str As String

 Str1 = "This is Line 1"

 Str2 = "This is Line 2"

 MsgBox Str1 & vbNewLine & Str2


End Sub

Output:

VBA-newline-vbNewLine

Adding new line in the Excel cell example

Writing in Excel cells is also simple.
You just need to ensure the cell is enabled “Wrap Text” for which you want to insert a new line.

You can see example of how to select “Wrap Text” in the above-linked tutorial.

To demonstrate that, we will write three-line text in the H8 cell as follows:

Code:

Sub vbNewLine_ex()

 'Adding vbNewLine in a cell
 Range("H8") = "Line Number 1" & vbNewLine & "Line Number 2" & vbNewLine & "Line Number 3"

End Sub

Output:

VBA-newline-vbnewline_

Using vbCrLf constant example

This is like pressing the Enter key.

The vbCrLf constant stands for Carriage Return and Line feed.

The code:

Sub newline_ex()

 Dim Str1 As String, Str As String
 Str1 = "This is Line 1"
 Str2 = "This is Line 2"

 'vbCrLf for adding new line
 MsgBox Str1 & vbCrLf & Str2

End Sub

Output:

VBA-newline-vbNewLine

Note: You might wonder why so many options for a line breaks in VBA? In order to understand the context, you might be interested in the history and reasons in a discussion in StackOverflow here.

Using vbCr constant example

You may also use the vbCr constant to add a line break between two or more sentences.

The vbCr returns to a line beginning. It represents a carriage-return character.

See an example below:

Code:

Sub vbCr_ex()

 'vbCr for adding new line
 MsgBox "This is an " & vbCr & "Example of" & vbCr & "cbCr constant!"

End Sub

Output:

VBA-newline-vbCr

vbLf example

The vbLf meant to go to the next line

It represents a linefeed character for print and display functions.

Example code

Sub vbLf_ex()

 'vbLf for adding new line
 MsgBox "This is an " & vbLf & "Example of" & vbLf & "vbLf constant!"

End Sub

Output:

VBA-newline-vbLf

Using Chr(10) ASCII for newline

In VBA, the Chr(10) return a linefeed character. You may also use it to add newlines in strings.