0

最近刚开始看VBA在Excel中通过IE访问网页的应用,对html编码没有经验,所以解决这个问题可能真的很简单...

我有一段代码(如下)应该导航到网站、访问表格并将数据提取到 Excel 中。但是,在看似随机的时间,我无法确定对象变量“TDelement”以某种方式被锁定,当我尝试通过循环访问下一个单元格时,Excel 会抛出错误 70:权限被拒绝。它不会一直发生,也不会发生在同一个表格单元格上。

Dim IE As Object
Dim TDElements As Object
Dim TDelement As Object
Dim Web_Address As String
Dim DteTm As Date

Web_Address = "http://www.bom.gov.au/fwo/IDQ65388/IDQ65388.040762.tbl.shtml"

' Access the Webpage
    IE.Navigate Web_Address
' Wait while IE loading...
    Do While IE.Busy
       Application.Wait DateAdd("s", 1, Now)
    Loop
' Find and Set Data Table Cells/object within webpage
     Set TDElements = IE.document.GetElementsByTagName("td")
' Pull each TDElement (table cell) from TDElements
     Rw = 1
     Col = 2
     For Each TDelement In TDElements
        If Col = 1 Then
           Col = 2
        ElseIf Col = 2 Then
           Col = 1
        End If
        If Col = 1 Then
           DteTm = TDelement.innerText
           Worksheets(1).Cells(Rw, Col).Value = DteTm
        ElseIf Col = 2 Then
           Worksheets(1).Cells(Rw, Col).Value = TDelement.innerText
        End If
        If Col = 2 Then
           Rw = Rw + 1
        End If
     Next

如果错误将在循环的一个周期内发生,则它发生在任一

DteTm = TDelement.innerText或者

Worksheets(1).Cells(Rw, Col).Value = TDelement.innerText,

If...Then显然,取决于陈述的结果。

经过一番谷歌搜索,普遍的共识似乎是错误 70 与变量的命名冲突有关(即尝试使用相同的变量名两次)。因此,我尝试在每个循环结束时添加Set TDelement = NothingbeforeNext以清除变量,但它并没有解决问题(并不那么令人惊讶;我以前从未遇到过像这样的循环中的变量问题)。

会不会有什么关系.innerText?尽管在我看到的关于从 IE 中提取数据的几乎所有论坛帖子中都提到了它,但 Excel 帮助文件中根本没有提到它......

对此的任何帮助将不胜感激。

4

1 回答 1

1

试试下面的代码:

Sub sample()

    Dim IE As Object
    Dim Web_Address As String

    Dim tblTR As Object
    Dim tblTD As Object


    Set IE = CreateObject("internetexplorer.application")
    Web_Address = "http://www.bom.gov.au/fwo/IDQ65388/IDQ65388.040762.tbl.shtml"

    ' Access the Webpage
    IE.Navigate Web_Address
    IE.Visible = True

Start:

    ' Wait while IE loading...
    Do While IE.Busy
        Application.Wait DateAdd("s", 5, Now)
    Loop
    ' Find and Set Data Table Cells/object within webpage
    Set tblTR = IE.document.GetElementsByTagName("tr")

    If tblTR Is Nothing Then GoTo Start

    Dim i As Integer
    i = 1

    For Each tblTD In tblTR
        If Not tblTD Is Nothing Then
            Worksheets(1).Cells(i, 1).Value = tblTD.all(0).innerText
            Worksheets(1).Cells(i, 2).Value = tblTD.all(1).innerText
        End If
        i = i + 1
    Next
End Sub
于 2013-03-12T04:57:33.713 回答