html - 一次复制 HTML 表格,无需循环单元格

标签 html vba excel

我想要复制 HTML 表格的内容。是否可以不循环遍历表格中的单元格来执行此操作? (我试图避免的示例: Under the comment 'Loop Through Each Table and Download it to Excel in Proper Format
我的 table 不是很大,所以循环是一种选择,只是徘徊是否有更好的选择。


我现在拥有的以及我更喜欢的建议方法:

'check all opened windows and find the one with PV output
For Each shlWindow In Shell.Windows
    If TypeName(shlWindow.document) = "HTMLDocument" And shlWindow.LocationName = "PV power estimate information" Then
        Set htmlPopupTables = shlWindow.document.getElementsBytagname("table")
        For Each htmlTabl In htmlPopupTables
            If htmlTabl.classname = "data_table" Then
                ' Question :
                ' htmlTabl.Copy 'or something similar
                ' then paste into my excel sheet
            End If
        Next htmlTabl
    End If
Next

我对 HTML 没有太多经验,所以即使是显而易见的事情也请毫不犹豫地说明。 :) 谢谢。

最佳答案

没有像htmlTable.Copy这样的方法,但您可以使用clipboard并将表格的html内容粘贴到Excel工作表中。

注意:需要引用internet控件、html对象库。和女士表格。数据将粘贴到事件工作表上的事件单元格。

Option Explicit

' Add reference to Microsoft Internet Controls
' Add reference to Microsoft HTML Object Library
' Add reference to Microsoft Forms 2.0 Object Library

Private Const url As String = "file:///c:/temp/table.html"

Sub test()
    Dim ie As SHDocVw.InternetExplorer
    Dim doc As MSHTML.HTMLDocument
    Dim tables As MSHTML.IHTMLElementCollection
    Dim table As MSHTML.HTMLTable
    Dim clipboard As MSForms.DataObject

    Set ie = New SHDocVw.InternetExplorer

    With ie
        .Visible = True
        .navigate url

        While .Busy Or .readyState <> READYSTATE_COMPLETE
            DoEvents
        Wend

        Set doc = .document
        Set tables = doc.getElementsByTagName("table")
        Set table = tables(0)
        Set clipboard = New MSForms.DataObject

        clipboard.SetText table.outerHTML
        clipboard.PutInClipboard
        ActiveSheet.Paste

        .Quit
    End With
End Sub

Demo HTML

<html>
    <head></head>
    <body>
        <table>
            <tr>
                <td>Cell 1</td>
                <td>Cell 2</td>
                <td>Cell 3</td>
            </tr>
            <tr>
                <td>Cell 4</td>
                <td>Cell 5</td>
                <td>Cell 6</td>
            </tr>
            <tr>
                <td>Cell 7</td>
                <td>Cell 8</td>
                <td>Cell 9</td>
            </tr>
        </table>
    </body>
</html>

Result

enter image description here

关于html - 一次复制 HTML 表格,无需循环单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29603458/

相关文章:

arrays - 创建一个空的二维数组

javascript - 智能手机书签

javascript - 如何保持textarea中的文本格式相同

html - 正文元素不在页面顶部

Excel,尝试索引,匹配,使用 VBA 查找值

java - 使用java无法在Excel中找到合并单元格

javascript - 用 jquery 替换 html 按钮

vba - 根据类别从列表中随机选择一个项目,根据不同的数字重复次数

vba - 运行时 13 类型不匹配

c# - 拖放在 DataGrid (WPF) 中不起作用