我刚刚开始在Excel中查看VBA的应用程序,通过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 = Nothing
之前添加Next
以清除每个循环结束时的变量,但它没有解决问题(并非所有令人惊讶的事情;我从未遇到过变量问题像这样的循环之前)。
它可能与.innerText
有关吗?尽管几乎每一篇关于从IE中提取数据的论坛帖都提到过,但在Excel帮助文件中却没有提到它......
对此的任何帮助将不胜感激。
答案 0 :(得分: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