Home > Software design >  How do I insert HTML elements into an HTML file with VBA
How do I insert HTML elements into an HTML file with VBA

Time:11-23

WHAT I ALREADY HAVE
I use the following for extracting data from an HTML file.
This example lists all Table Rows within an HTML file

Dim IE As InternetExplorer
Dim HTMLdoc As HTMLDocument
Dim TRelements As IHTMLElementCollection
Dim TRelement As HTMLTableCell
Dim r As Long
Set IE = New InternetExplorer
With IE
    .Navigate filePath
    While .Busy Or .ReadyState <> READYSTATE_COMPLETE: DoEvents: Wend
    Set HTMLdoc = .Document
End With
Set TRelements = HTMLdoc.getElementsByTagName("TR")

This allows me to pinpoint data in the following way (5th row, 1st cell), Example:

A = TRelements.Item(5).ChildNodes.Item(1).innerText

WHAT I AM LOOKING FOR
I'd like to insert a new cell (TD-element) at the beginning of a row (TR-element)

DESIRED OUTCOME

NAME SURNAME
Walter White

New TD-element for DOB

DOB NAME SURNAME
09-07-58 Walter White

CodePudding user response:

In the example below I use Element.insertAdjacentHTML() and Element.insertAdjacentElement() to insert the new cells.

Sub Example()
    Dim IE As InternetExplorer
    Dim HTMLdoc As HTMLDocument
    Dim TRelements As IHTMLElementCollection
    Dim TRelement As HTMLTableCell
    Dim r As Long
    Set IE = New InternetExplorer
    With IE
        .navigate filePath
        While .Busy Or .readyState <> READYSTATE_COMPLETE: DoEvents: Wend
        Set HTMLdoc = .document
    End With        
    
    Set TRelements = HTMLdoc.getElementsByTagName("TR")
    Dim TR As HTMLTableRow
    Set TR = TRelements(0)
    TR.insertAdjacentHTML "afterbegin", "<TH>DOB</TH>"
    
    Dim TD As HTMLTableCell
    Set TD = HTMLdoc.createElement("TD")
    
    Set TR = TRelements(1)
    TD.innerText = "09-07-58"
    TR.insertAdjacentElement "afterbegin", TD
    
    IE.Visible = True
End Sub
  • Related