0

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

1 Answer 1

2

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

This subroutine will update the original file.

Sub OverWriteHTMLDocument(Document As HTMLDocument, FilePath As String)
    Rem VBA OpenTextFile: https://analystcave.com/vba-filesystemobject-fso-in-excel/vba-opentextfile/
    
    Const ForReading = 1, ForWriting = 2, ForAppending = 8 'Need to define constants manually
    Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0 'Need to define constants manually
    Dim Url As String
    Url = Replace(Document.Url, "file://", "", , , vbTextCompare)
    With CreateObject("Scripting.FileSystemObject").OpenTextFile(Url, ForWriting, True, TristateFalse)
        .WriteLine Document.DocumentElement.outerHTML
        .Close
    End With
   
End Sub
Sign up to request clarification or add additional context in comments.

2 Comments

That works, what is the proper way to save the changes to the document?
@MK01111000 Thanks for accepting my answer. I added a subroutine that will update the file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.