Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert line break in wrapped cell via code

Tags:

excel

vba

Is it possible to insert line break in a wrapped cell through VBA code? (similar to doing Alt-Enter when entering data manually)

I have set the cell's wrap text property to True via VBA code, and I am inserting data into it also through VBA code.

like image 653
Sarika.S Avatar asked Mar 28 '12 03:03

Sarika.S


People also ask

How do you put a line break in an Excel formula?

It's easy to add a line break when you're typing in an Excel worksheet. Just click where you want the line break, and press Alt + Enter.

How do I create a new line in a cell in Excel VBA?

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 VBA. read more. For example, CHR (10) is the code to insert a new line in VBA.

How do I create a new line in a Messagebox in VBA?

If you want to force a new line in a message box, you can include one of the following: The Visual Basic for Applications constant for a carriage return and line feed, vbCrLf. The character codes for a carriage return and line feed, Chr(13) & Chr(10).


2 Answers

Yes. The VBA equivalent of AltEnter is to use a linebreak character:

ActiveCell.Value = "I am a " & Chr(10) & "test" 

Note that this automatically sets WrapText to True.

Proof:

Sub test() Dim c As Range Set c = ActiveCell c.WrapText = False MsgBox "Activcell WrapText is " & c.WrapText c.Value = "I am a " & Chr(10) & "test" MsgBox "Activcell WrapText is " & c.WrapText End Sub 
like image 102
brettdj Avatar answered Oct 13 '22 08:10

brettdj


You could also use vbCrLf which corresponds to Chr(13) & Chr(10). As Andy mentions in the comment below, you might be better off using ControlChars.Lf instead though.

like image 27
Andy Brown Avatar answered Oct 13 '22 08:10

Andy Brown