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
Just do Ctrl + Enter inside the text box
Yes there are two way to add a line feed:
Use the existing function from VBA vbCrLf
in the string you want to add a line feed, as such:
Dim text As String
text = "Hello" & vbCrLf & "World!"
Worksheets(1).Cells(1, 1) = text
Use the Chr()
function and pass the ASCII characters 13 and 10 in order to add a line feed, as shown bellow:
Dim text As String
text = "Hello" & Chr(13) & Chr(10) & "World!"
Worksheets(1).Cells(1, 1) = text
In both cases, you will have the same output in cell (1,1) or A1.
You could also use vbCrLf
which corresponds to Chr(13)
& Chr(10)
.
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