Vbcrlf: The Visual Basic Carriage Return Line Feed
To facilitate the reading of a messages by users or readers – especially long messages – it is necessary to format it conveniently through new lines, alignment, new paragraphs, etc. For a specialized word processing software like MS Word, this is easy. For example, to go to a next line, you just have to press the ENTER key.
In this article, you will learn how to use the Vbcrlf in VBA.
What is Vbcrlf?
Vbcrlf stands for “Visual Basic Carriage Return Line Feed.” It is a VBA constant for the carriage return and line feed characters.
To better understand Vbcrlf, you need to recall the days of old manual typewriters – if you’re old enough to remember – to get the origins of this. There are two distinct actions needed to start a new line of text:
- Move the typing head back to the left. On a typewriter, this is done by moving the roll which carries the paper (the “carriage”) back to the right. This is a carriage return.
- Move the paper up by the width of one line. This is a line feed.
Vbcrlf is a combination of the two actions explained above: the Carriage Return (VbCr) that moves the cursor back to the beginning of the line and the Line feed (VbLf) that moves the cursor position down one line. In other words, vbCrLf is to VBA what the ENTER key is to a word processor.
Launch MS Excel, open the VBA editor and write the following code:
Sub TestVbcrlf() MsgBox "Hello, This is an example to show how to format a message in VBA. Hope it will be helpful" End Sub
After running the code, you will get the following result:
As you can see, the message only goes to the next line when the number of characters of the first line is reached.
When the sentences are too long and poorly presented like the one above, readers are usually not motivated to read them. To solve that, the message can be presented in many lines by inserting Vbcrlf at the beginning of each new line as below:
Sub TestVbcrlf() MsgBox "Hello." & Vbcrlf & "This is an example to show how to format a message in VBA." & Vbcrlf & "Hope it will be helpful." End Sub
The trick is to insert the line breaker
& Vbcrlf & at the beginning of the text. Don’t forget to put each sentence or text in double inverted commas:
After running the code, you will have the following message with three easily readable lines.
Note: if you want to insert an empty line between two sentences, you should add a second line breaker to the first one as in the following example:
Sub TestVbcrlf() MsgBox "Hello.” & Vbcrlf & Vbcrlf & "This is an example to show how to format a message in VBA." & Vbcrlf & Vbcrlf & "Hope it will be helpful." End Sub
There are many other constants that can be used in VBA to obtain the same result as with Vbcrlf.
Vbcrlf by any of them in the above code examples to see the result.
This article was about the use of the Visual Basic Carriage Return Line Feed (Vbcrlf) in the proper presentation of a message. Hope it has been useful for you.