I'm trying to insert HTML/RTF formatted text into a single Excel cell, preserving text formatting (colour, bold, italic etc.).
The problem is that if the text contains line breaks (<br>
), parts of the text between the breaks is inserted into separate cells.
I tried <b style="mso-data-placement:same-cell;" />
, but it seems to be ignored by Excel's parser and treated like a normal <br>
.
A lot of topics on forums say that mso-data-placement:same-cell lets you have new line breaks inside a cell, but in my case this style is ignored.
How do I achieve text formatting and line breaks when pasting text into a single cell?
My code (simplified a bit):
Private Sub Worksheet_Change2(ByVal Target As Range, ByVal sht As Worksheet)
Dim objData As MSForms.DataObject
Dim sHTML As String
Application.EnableEvents = False
Set objData = New MSForms.DataObject
sHTML = "<html>ABC<br>EFG" & "<br style=" & Chr(34) & "mso-data-placement:same-cell;" & Chr(34) & " />" & "XYZ</html>"
objData.SetText sHTML
objData.PutInClipboard
sht.PasteSpecial Format:="Unicode Text" ', NoHTMLFormatting:=False
Application.EnableEvents = True
End Sub