一次复制HTML表,而不循环遍历单元格

时间:2015-04-13 10:47:21

标签: html vba excel-vba excel

我想复制HTML表的内容。是否可以在表中执行而不通过单元格? (我试图避免的例子:Under the comment 'Loop Through Each Table and Download it to Excel in Proper Format 我的表格不是很大,所以循环是一个选项,如果有更好的选择,只是徘徊。


我现在所拥有的和建议的方法我更喜欢:

'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没有多少经验,所以即使是显而易见的,也不要犹豫。 :)谢谢。

1 个答案:

答案 0 :(得分:5)

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

注意:有必要引用互联网控件,html对象库。和ms形式。数据将粘贴到活动工作表上的活动单元格中。

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
  

演示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>
  

结果

enter image description here