【问题标题】:inserting a HTML table cell into a excel sheet cell with no id将 HTML 表格单元格插入到没有 id 的 excel 表格单元格中
【发布时间】:2016-07-07 06:50:37
【问题描述】:

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

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

我无法通过 id 获取元素,所以我创建了两个循环来逐个元素地查找元素。代码可以找到元素(在我的例子中,单词“费用” 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

提前致谢

【问题讨论】:

  • 11 只是更多的列。从您的示例数据很难说,但可能有 1 个或 2 个或更多。您可以使用debug.print 进行循环以在第一次找出它,而不是相应地调整代码。因此,如果它是第 2 列,它将是 tr.Cells(2).innertext

标签: html vba excel internet-explorer


【解决方案1】:

Scott 是对的,没有理由遍历所有 td。

 For Each tr In colTR

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

 Next 

【讨论】:

  • 很高兴为您提供帮助。先生!