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

VBA add new line

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 using 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 a 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 exampl 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 wrap text

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 line breaks in VBA. 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) returns a linefeed character. You may also use it to add new lines in strings.

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we solve the mysteries of coding together!