Search code examples
vbaexcelhtml-parsing

HTML Text with tags to formatted text in an Excel cell


Is there a way to take HTML and import it to excel so that it is formatted as rich text (preferably by using VBA)? Basically, when I paste to an Excel cell, I'm looking to turn this:

<html><p>This is a test. Will this text be <b>bold</b> or <i>italic</i></p></html>

into this:

This is a test. Will this text be bold or italic


Solution

  • Yes it is possible. In fact let Internet Explorer do the dirty work for you.

    MY ASSUMPTIONS

    1. I am assuming that the html text is in Cell A1 of Sheet1. You can also use a variable instead.
    2. If you have a column full of html values, then simply put the below code in a loop

    CODE

    Sub Sample()
        Dim Ie As Object
        
        Set Ie = CreateObject("InternetExplorer.Application")
        
        With Ie
            .Visible = False
            
            .Navigate "about:blank"
            
            .document.body.InnerHTML = Sheets("Sheet1").Range("A1").Value
            
            .document.body.createtextrange.execCommand "Copy"
            ActiveSheet.Paste Destination:=Sheets("Sheet1").Range("A1")
            
            .Quit
        End With
    End Sub
    

    SNAPSHOT

    enter image description here