将HTML表格单元格插入到没有id的Excel工作表单元格中

时间:2016-07-06 21:59:22

标签: html excel vba excel-vba internet-explorer

我试图通过使用函数将HTML表格中的单元格提取到excel单元格中。表格是这样的:

                   |   1Q    |   2Q    |   3Q    |
         income    |   23    |   34    |   22    |
         expenses  |   11    |   19    |   10    |
                                  .
                                  .
                                  .

我无法通过id获取元素,所以我创建了两个循环来逐个元素地查找。代码可以找到元素(在我的例子中,单词“expenses”col1 row2)但我不知道如何获取右边的单元格值(在这种情况下为11)

Dim IE As Object
Dim doc As Object
Dim colTR As Object
Dim colTD As Object
Dim tr As Object
Dim td As Object
Set IE = CreateObject("InternetExplorer.Application")

IE.Visible = True
IE.Navigate "www.mywebpage.com"

Do Until IE.ReadyState = 4
    DoEvents
Loop

Set doc = IE.Document

Set colTR = doc.GetElementsByTagName("TR")
For Each tr In colTR
    Set colTD = tr.GetElementsByTagName("TD")
    For Each td In colTD
        If td.innertext = "expenses" Then
        TheValueIWant = tr.item(1).innertext
        End If
    Next td
Next tr

IE.Quit

Set IE = Nothing
Set doc = Nothing
Set colTR = Nothing
Set colTD = Nothing
Set td = Nothing
Set tr = Nothing

提前致谢

1 个答案:

答案 0 :(得分:0)

斯科特是对的,没有理由遍历所有的tds。

 For Each tr In colTR

    If tr.Cells(0).innerText = "expenses" Then
        TheValueIWant = tr.Cells(1).innerText
        MsgBox TheValueIWant
    End If

 Next