excel 如何使用VBA将HTML元素插入HTML文件

mkh04yzy  于 2022-11-26  发布在  其他
关注(0)|答案(1)|浏览(106)

"我已经拥有的"
我使用以下代码从HTML文件中提取数据。
本示例列出HTML文件中的所有表行

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")

这使我可以通过以下方式精确定位数据(第5行,第1个单元格),例如:

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

我在寻找什么

我想在一行(TR元素)的开头插入一个新单元格(TD元素)

预期结果

| 名称|姓名|
| - -|- -|
| 瓦尔特|白色|
DOB的新TD元素
| 出生日期|名称|姓名|
| - -|- -|- -|
| 一九五八年七月九日|瓦尔特|白色|

1l5u6lss

1l5u6lss1#

在下面的示例中,我使用Element.insertAdjacentHTML()Element.insertAdjacentElement()插入新单元格。

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

此子例程将更新原始文件。

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

相关问题