5 Ways of Adding newline in VBA (Carriage Return)
In VBA, a newline can be added by using following: vbNewLine constant vbCrLf constant vbCr constant
Adding a new line in VBA
In VBA, a newline can be added by using 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 assigned both texts after declaration.
In a MsgBox, we will concatenate both strings and add a newline by the vbNewLine constant. See the code and output below:
The code:
1 2 3 4 5 6 7 8 9 10 11 12 |
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:
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 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:
1 2 3 4 5 6 |
Sub vbNewLine_ex() 'Adding vbNewLine in a cell Range("H8") = "Line Number 1" & vbNewLine & "Line Number 2" & vbNewLine & "Line Number 3" End Sub |
Output:
Using vbCrLf constant example
This is like pressing the Enter key. The vbCrLf constant stands for Carriage Return and Line feed.
The code:
1 2 3 4 5 6 7 8 9 10 |
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:
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
The vbCr returns to a line beginning. It represents a carriage-return character.
You may also use the vbCr constant to add a line break between two or more sentences. See an example below:
Code:
1 2 3 4 5 6 |
Sub vbCr_ex() 'vbCr for adding new line MsgBox "This is an " & vbCr & "Example of" & vbCr & "cbCr constant!" End Sub |
Output:
vbLf example
The vbLf meant to go to the next line
It represents a linefeed character for print and display functions.
Example code
1 2 3 4 5 6 |
Sub vbLf_ex() 'vbLf for adding new line MsgBox "This is an " & vbLf & "Example of" & vbLf & "vbLf constant!" End Sub |
Output:
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.