Line break in excel vba

Home / VBA / How to Add a Line Break in a VBA Code (Single Line into Several Lines)

While writing VBA codes, you might face a situation where you have a lengthy line of code, which makes it hard to read it for everyone. In that case, the best way is to use the VBA Line Break Character, which you have in the below example.

In the first macro, you have only one long line but in the second macro, that same line is broken into three lines with line-continuation characters.

Now, if you look closely, the first two lines have an underscore at the end.

If you want to break a line into two or more, you need to type a space followed by an underscore.

One of the most significant benefits of using a line break is to make a code structured and easy to read.

To enter a VBA line break you can use the following steps.

  1. First, click on the character from where you want to break the line.
  2. Next, type a space( ).
  3. After that, type an underscore(_).
  4. In the end, hit enter to break the line.

But there is one thing that you need to take care of; you can’t add a line break in the middle of the argument.

Multiple Lines of Code on One Line

VBA also allows you to write multiple lines of code on the same line. Let’s say you want to combine below two lines of code in a single line. You can use a colon (:) for that.

So it will be:

I know this question is really old, but as I had the same needs, after searching SO and google, I found pieces of answers but nothing usable. So with those pieces and bites I made my solution that I share here.

What I needed

  1. Knowing the column width in pixels
  2. Be able to measure the length of a string in pixels in order to cut it at the dimension of the column

What I found

  1. About the width in pixels of a column, I found this in Excel 2010 DocumentFormat :

To translate the value of width in the file into the column width value at runtime (expressed in terms of pixels), use this calculation:
=Truncate(((256 * {width} + Truncate(128/{Maximum Digit Width}))/256)*{Maximum Digit Width})
Even if it’s Excel 2010 format, it’s still working in Excel 2016. I’ll be able to test it soon against Excel 365.

  1. About the width of a string in pixels, I used the solution proposed by @TravelinGuy in this question, with small corrections for typo and an overflow. By the time I’m writing this the typo is already corrected in his answer, but there is still the overflow problem. Nevertheless I commented his answer so there is everything over there for you to make it works flawlessly.

What I’ve done

Code three recursive functions working this way :

  1. Function 1 : Guess the approximate place where to cut the sentence so if fits in the column and then call Function 2 and 3 in order to determine the right place. Returns the original string with CR (Chr(10)) characters in appropriate places so each line fits in the column size,
  2. Function 2 : From a guessed place, try to add some more words in the line while this fit in the column size,
  3. Function 3 : The exact opposite of function 2, so it retrieves words to the sentence until it fits in the column size.

Here is the code

Sub SplitLineTest()
    Dim TextRange As Range
    Set TextRange = FeuilTest.Cells(2, 2) 

 'Take the text we want to wrap then past it in multi cells
    Dim NewText As String
    NewText = SetCRtoEOL(TextRange.Value2, TextRange.Font.Name, TextRange.Font.Size, xlWidthToPixs(TextRange.ColumnWidth) - 5) '-5 to take into account 2 white pixels left and right of the text + 1 pixel for the grid
    
'Copy each of the text lines in an individual cell
    Dim ResultArr() As String
    ResultArr() = Split(NewText, Chr(10))
    TextRange.Offset(2, 0).Resize(UBound(ResultArr) + 1, 1).Value2 = WorksheetFunction.Transpose(ResultArr())
End Sub


Function xlWidthToPixs(ByVal xlWidth As Double) As Long
'Fonction to convert the size of an Excel column width expressed in Excel unit(Range.ColumnWidth) in pixels
'Parameters :   - xlWidth : that is the width of the column Excel unit
'Return :       - The size of the column in pixels
    
    Dim pxFontWidthMax As Long
    
    'Xl Col sizing is related to workbook default string configuration and depends of the size in pixel from char "0". We need to gather it
    With ThisWorkbook.Styles("Normal").Font
        pxFontWidthMax = pxGetStringW("0", .Name, .Size)    'Get the size in pixels of the '0' character
    End With
    
    'Now, we can make the calculation
    xlWidthToPixs = WorksheetFunction.Floor_Precise(((256 * xlWidth + WorksheetFunction.Floor_Precise(128 / pxFontWidthMax)) / 256) * pxFontWidthMax) + 5
End Function


Function SetCRtoEOL(ByVal Original As String, ByVal FontName As String, ByVal FontSize As Variant, ByVal pxAvailW) As String
'Function aiming to make a text fit into a given number of pixels, by putting some CR char between words when needed.
'If some words are too longs to fit in the given width, they won't be cut and will get out of the limits given.
'The function works recursively. Each time it find an End Of Line, it call itself with the remaining text until.
'The recursive process ends whent the text fit in the given space without needing to be truncated anymore
'Parameters :   - Original : The text to fit
'               - FontName : Name of the font
'               - FontSize : Size of the font
'               - pxAvailW : Available width in pixels in wich we need to make the text fit
'Return :       - The orignal text with CR in place of spaces where the text needs to be cut to fit the width
    
    'If we got a null string, there is nothing to do so we return a null string
    If Original = vbNullString Then Exit Function
    
    Dim pxTextW As Long
    
    'If the text fit in, may be it's the original or this is end of recursion. Nothing to do more than returne the text back
    pxTextW = pxGetStringW(Original, FontName, FontSize)
    If pxTextW < pxAvailW Then
        SetCRtoEOL = Original
        Exit Function
    End If
    
    'The text doesn't fit, we need to find where to cut it
    Dim WrapPosition As Long
    Dim EstWrapPosition As Long
    EstWrapPosition = Len(Original) * pxAvailW / pxTextW   'Estimate the cut position in the string given to a proportion of characters
    If pxGetStringW(Left(Original, EstWrapPosition), FontName, FontSize) < pxAvailW Then
        'Text to estimated wrap position fits in, we try to see if we can fits some more words
        WrapPosition = FindMaxPosition(Original, FontName, FontSize, pxAvailW, EstWrapPosition)
    End If
        
    'If WrapPosition = 0, we didn't get a proper place yet, we try to find the previous white space
    If WrapPosition = 0 Then
        WrapPosition = FindMaxPositionRev(Original, FontName, FontSize, pxAvailW, EstWrapPosition)
    End If
        
    'If WrapPosition is still 0, we are facing a too long word for the pxAvailable. We'll cut after this word what ever. (Means we must search for the first white space of the text)
    If WrapPosition = 0 Then
        WrapPosition = InStr(Original, " ")
    End If
    
    If WrapPosition = 0 Then
        'Words too long to cut, but nothing more to cut, we return it as is
        SetCRtoEOL = Original
    Else
        'We found a wrap position. We recurse to find the next EOL and construct our response by adding CR in place of the white space
        SetCRtoEOL = Left(Original, WrapPosition - 1) & Chr(10) & SetCRtoEOL(Right(Original, Len(Original) - WrapPosition), FontName, FontSize, pxAvailW)
    End If
End Function


Function FindMaxPosition(ByVal Text As String, ByVal FontName As String, ByVal FontSize As Variant, ByVal pxAvailW, ByVal WrapPosition As Long) As Long
'Function that finds the maximum number of words fitting in a given space by adding words until it get out of the maximum space
'The function is inteded to work on text with a "guessed" wrap position that fit in the space allowed
'The function is recursive. Each time it guesses a new position and the word still fits in the space, it calls itself with a further WrapPosition
'Parameters :   - Text : The text to fit
'               - FontName : Name of the font
'               - FontSize : Size of the font
'               - pxAvailW : Available width in pixels in wich we need to make the text fit
'               - WrapPosition : The initial wrap position, positionned someware in the text (WrapPosition < len(Text)) but inside pxAvailW
'Return :       - The position were the text must be wraped to put as much words as possible in pxAvailW, but without getting outside of it. If no position can be found, returns 0

    Dim NewWrapPosition As Long
    Static isNthCall As Boolean
    
    'Find next Whitespace position
    NewWrapPosition = InStr(WrapPosition, Text, " ")
            
    If NewWrapPosition = 0 Then Exit Function                                               'We can't find a wrap position, we return 0
    If pxGetStringW(Left(Text, NewWrapPosition - 1), FontName, FontSize) < pxAvailW Then    '-1 not to take into account the last white space
        'It still fits, we can try on more word
        isNthCall = True
        FindMaxPosition = FindMaxPosition(Text, FontName, FontSize, pxAvailW, NewWrapPosition + 1)
    Else
        'It doesnt fit. If it was the first call, we terminate with 0, else we terminate with previous WrapPosition
        If isNthCall Then
            'Not the first call, we have a position to return
            isNthCall = False                               'We reset the static to be ready for next call of the function
            FindMaxPosition = WrapPosition - 1              'Wrap is at the first letter of the word due to the function call FindMax...(...., NewWrapPosition + 1). The real WrapPosition needs to be minored by 1
        Else
            'It's the first call, we return 0 | Strictly speaking we can remove this part as FindMaxPosition is already 0, but it make the algo easier to read
            FindMaxPosition = 0
        End If
    End If
End Function


Function FindMaxPositionRev(ByVal Text As String, ByVal FontName As String, ByVal FontSize As Variant, ByVal pxAvailW, ByVal WrapPosition As Long) As Long
'Function working backward of FindMaxPosition. It finds the maximum number of words fitting in a given space by removing words until it fits the given space
'The function is inteded to work on text with a "guessed" wrap position that fit in the space allowed
'The function is recursive. Each time it guesses a new position and the word still doesn't fit in the space, it calls itself with a closer WrapPosition
'Parameters :   - Text : The text to fit
'               - FontName : Name of the font
'               - FontSize : Size of the font
'               - pxAvailW : Available width in pixels in wich we need to make the text fit
'               - WrapPosition : The initial wrap position, positionned someware in the text (WrapPosition < len(Text)), but outside of pxAvailW
'Return :       - The position were the text must be wraped to put as much words as possible in pxAvailW, but without getting outside of it. If no position can be found, returns 0

    Dim NewWrapPosition As Long
    
    NewWrapPosition = InStrRev(Text, " ", WrapPosition)
    'If we didn't found white space, we are facing a "word" too long to fit pxAvailW, we leave and return 0
    If NewWrapPosition = 0 Then Exit Function
    
    If pxGetStringW(Left(Text, NewWrapPosition - 1), FontName, FontSize) >= pxAvailW Then   '-1 not to take into account the last white space
        'It still doesnt fits, we must try one less word
        FindMaxPositionRev = FindMaxPositionRev(Text, FontName, FontSize, pxAvailW, NewWrapPosition - 1)
    Else
        'It fits, we return the position we found
        FindMaxPositionRev = NewWrapPosition
    End If
End Function

Known limitations

This code will work as long as the text in the cell has only one font and one font size. Here I assume that the font is not Bold nor Italic, but this can be easily handled by adding few parameters as the function measuring the string length in pixels is already able to do it.
I’ve made many test and I always got the same result than the autowrap function of Excel worksheet, but it may vary from one Excel version to an other. I assume it works on Excel 2010, and I tested it with success in 2013 and 2016. Fo others I don’t know.
If you need to handle cases where fonts type and/or attributs vary inside a given cell, I assume it’s possible to achieve it by testing the text in the cell character by character by using the range.caracters property. It should be really slower, but for now, even with texts to split in almost 200 lines, it takes less than one instant so maybe it’s viable.

Return to VBA Code Examples

When working with strings in VBA, use vbNewLine, vbCrLf or vbCR to insert a line break / new paragraph.

This article will also discuss how to use use the line continuation character in order to continue a statement in your actual VBA code on a new line.

Using vbNewLine

The following code shows you how you would use vbNewLine in order to put the second text string on a new line in the Immediate window:

Sub UsingvbNewLine()

Dim StringOne As String
Dim StringTwo As String

StringOne = "This is String One"
StringTwo = "This is String Two"

Debug.Print StringOne & vbNewLine & StringTwo

End Sub

The result is:

Using vbNewLine in VBA to add new lines

Using vbCrLf

The following code shows you how you would use vbCrLf in order to put the second text string on a new line in a shape:

Sub UsingvbCrLf()

Dim StringOne As String
Dim StringTwo As String

StringOne = "This is String One"
StringTwo = "This is String Two"

ActiveSheet.Shapes.AddShape(msoShapeRectangle, 15, 15, 100, 50).Select

With Selection
.Characters.Text = StringOne & vbCrLf & StringTwo
End With

End Sub

The result is:

Using vbCrLF to add new lines in VBA

Using vbCR

The following code shows you how you would use vbCR in order to put the second text string on a new line in a message box:

Sub UsingvbCR()

Dim StringOne As String
Dim StringTwo As String

StringOne = "This is String One"
StringTwo = "This is String Two"

MsgBox StringOne & vbCr & StringTwo

End Sub

The result is:

Using vbCR to insert a new line in VBA

Continuing a Statement in VBA

You can use the line continuation character (“_” aka the underscore) to continue a statement from one line to the next in your VBA code. The following code shows you how to use the line continuation character:

Sub LineContinuation ()

If Range("b1").Value > 0 Then _
   Range("c1").Value = "Greater Than Zero"
End Sub

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

In this post, you’ll learn about the usage of vbNewLine, vbCrLf or vbCR to insert line break in your Excel spreadsheet using Excel VBA.

vbNewLine in Excel VBA

Below is a code snippet demonstrating how you can use vbNewLine to insert new line after the first string.

Sub InsertNewLinevbNewLine()

Dim str1 As String
Dim str2 As String

str1 = "String 1"
str2 = "String 2"

Debug.Print str1 & vbNewLine & str2

End Sub

vbCrLf in Excel VBA

The below code snippet show how you can insert new line using vbCrLf using Excel VBA.

Sub InsertNewLinevbCrLf()

Dim str1 As String
Dim str2 As String

str1 = "String 1"
str2 = "String 2"

Debug.Print str1 & vbCrLf & str2

End Sub

The below code snippet demonstrates how you can use vbCR to insert new line using Excel VBA.

Sub InsertNewLinevbCr()

Dim str1 As String
Dim str2 As String

str1 = "String 1"
str2 = "String 2"

Debug.Print str1 & vbCr & str2

End Sub
New Line or Carriage Return in Excel VBA

New Line in VBA MsgBox

Aligning the sentence is very important to convey the right message to the users or readers. To make the sentence proper, we use “new paragraph” or newline as one of the techniques. It usually happens in Word documents. If you have this question, then this article eases your worry. Follow this article completely to learn about the new line in VBA.

In Excel, when we want to insert a new line character, we either press Ctrl + Enter to insert a new line break or use the CHR function with 10. In VBA programming, using newline breakers to frame sentences is almost inevitable. But the question is, how can we insert a new VBA line breaker?

Table of contents
  • New Line in VBA MsgBox
    • How to Insert New Line in VBA MsgBox?
    • Example #1 – Insert New Line in VBA MsgBox Using “vbNewLine.”
    • Example #2 – Insert New Line Using “Char (10)”
    • Example #3 – Insert New Line Using “vbCrLf, vbCr, vbLf”
    • Recommended Articles

VBA New Line

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA New Line (wallstreetmojo.com)

How to Insert New Line in VBA MsgBox?

We have seen people using several ways to insert newlines in VBA. So, in this article, we have decided to show you each of them in detail.

Before we show you how to insert a new line in VBA, let us show you why you need to insert lines in VBA. For example, look at the below image.

insert new line 1

We have framed the sentence in the message without inserting any new lines in the VBA codesVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more. Now, look at the below image.

insert new line 2

Suppose you look at the above two images, which one looks neat and clean. Both convey the same message but having a look at both the images. You decide which is better for you and continue reading to learn the second image.

Example #1 – Insert New Line in VBA MsgBox Using “vbNewLine.”

To insert the new line in VBA, we can use the VBA ConstantUsing the VBA “Const” word we can declare constants just like how we declare variables using the “Dim” keyword. After declaring a constant, it cannot be modified later.read more vbNewLine.”

As the name says, it will insert a new line between sentences or characters. For example, look at the below code.

Code:

Sub Type_Example1()

  MsgBox "Hi Welcome to VBA Forum!!!. We will show you how to insert new line in this article"

End Sub

In the above code, we have two sentences. The first one is “Hi, Welcome to VBA Forum!” And the second one is, “We will show you how to insert a new line in this article.”

The above shows these sentences in a single line, only like the below image.

VBA New Line 1

When the sentences are too large, it often creates ambiguity in the readers’ minds, or it doesn’t look pleasant. As a result, readers do not want to read at all.

To avoid all these things, we can show the message in two lines instead of the default line after the first line sentence closes the double quotes and puts the ampersand (&) symbol.

Code:

Sub Type_Example1()

  MsgBox "Hi Welcome to VBA Forum!!!."&

End Sub

VBA New Line Example 1

After the ampersand (&) symbol, press the spacebar and get the VBA constant “vbNewLine.”

Code:

Sub Type_Example1()

  MsgBox "Hi Welcome to VBA Forum!!!." & vbNewLine

End Sub

VBA New Line Example 1-1

After the constant “vbNewLine,” press one more time space bar and add the ampersand (&) symbol.

Code:

Sub Type_Example1()

  MsgBox "Hi Welcome to VBA Forum!!!." & vbNewLine &

End Sub

VBA New Line Example 1-2

After the second ampersand (&) symbol, type one more space character, and add the next line sentence in double quotes.

Code:

Sub Type_Example1()

  MsgBox "Hi Welcome to VBA Forum!!!." & vbNewLine & "We will show you how to insert new line in this article"

End Sub

Example 1-3

We have done it. Run the code to see the two sentences in two lines.

Example 1-4

If you are unhappy with the single line breaker, insert one more line breaker by entering one more new line inserter in VBA MsgboxVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more using “vbNewLine.”

Code:

Sub Type_Example1()

MsgBox "Hi Welcome to VBA Forum!!!." & vbNewLine & vbNewLine & "We will show you how to insert new line in this article"

End Sub

Example 1-5

Above bold and underlined words will insert two line breakers between sentences, and the result is as below.

Example 1-6

Example #2 – Insert New Line Using “Char (10)”

To a new line instead of “vbNewLine,” we can also use the function CHR to insert a new line in VBAVBA CHR is an inbuilt text/string function that returns the printable and non-printable characters present on the keyboard and understands the computer assigned with specific ASCII codes.read more. For example, CHR (10) is the code to insert a new line in VBA. Below is an example of the same.

Code:

Sub Type_Example1()

MsgBox "Hi Wecome to VBA Forum!!!." & Chr(10) & Char(10) & "We will show you how to insert new line in this article"

End Sub

Example #3 – Insert New Line Using “vbCrLf, vbCr, vbLf”

We can also use the constants “vbCrLf, vbCr, vbLf” to insert the new line breaker. Below are examples of the same.

Code:

Sub Type_Example1()

MsgBox "Hi Welcome to VBA Forum!!!" & vbLf & vbLf & "We will show you how to insert new line in this article"

End Sub

Code:

Sub Type_Example1()

MsgBox "Hi Welcome to VBA Forum!!!" & vbCr & vbCr & "We will show you how to insert new line in this article"

End Sub

Code:

Sub Type_Example1()

MsgBox "Hi Welcome to VBA Forum!!!" & vbCrLf & vbCrLf & "We will show you how to insert new line in this article"

End Sub

You can download this VBA New Line Excel here. VBA New Line Excel Template

Recommended Articles

This article has been a guide to VBA New Line. Here, we learned how to insert a new line in VBA MsgBox Using “vbNewLine,” “Char(10),” and “vbCrLf, vbCr, vbLf” to insert the new line breaker along with practical examples and download the Excel template. Below are some useful Excel articles related to VBA: –

  • Excel VBA Selection Range
  • AND Function in VBA
  • VBA Excel Pivot Table
  • VBA Today Function

Понравилась статья? Поделить с друзьями:
  • Line borders for word
  • Liable sentence with the word
  • Line border in word
  • Li daikin word of honor
  • Line below text in word