Search code examples
htmlvbahead

VBA code to edit HTML file without losing <head>...</head> information


I am trying to create a excel macro to edit an html file I have on my disk. I am using something like this:

Sub changeImg()

    Dim dom As HTMLDocument
    Dim img As Object
    Dim src As String

    Set dom = CreateObject("htmlFile")

    Open "C:\temp\test.html" For Input As #1
        src = Input$(LOF(1), 1)
    Close #1

    dom.body.innerHTML = src

    Set img = dom.getelementsbytagname("img")(0)

    img.src = "..."

    Open "C:\temp\test.html" For Output As #1
        Print #1, dom.DocumentElement.outerHTML
    Close #1


End Sub

The problem is that I lose all info inside < head > < \head > from my start file. I can't figure it out how to keep all the html code and only replace what I want using getElementById. Any help or orientation is appreciated. Thanks.


Solution

  • Try something like this:

    Dim doc
    Set doc = CreateObject("htmlfile")
    
    doc.Open "text/html"
    'next line could use content read from a file...
    doc.write "<html><head><title>The title</title></head><body>The body</body></html>"
    doc.Close
    
    Debug.Print doc.Title
    Debug.Print doc.body.innerText
    
    doc.Title = "New Title here"
    doc.body.innerHTML = "New body here"
    
    Debug.Print doc.Title
    Debug.Print doc.body.innerText
    
    Debug.Print doc.DocumentElement.outerHTML 'or write to file...