我使用 VBA 和 IE 自动化打开网页、登录、通过填写一些输入字段并单击网页的特定按钮进行导航,最后从中获取一些数据。
在导航时,我为网页中的元素设置了几个变量。接下来,我单击网页的按钮,然后单击一些变量(ele0
和ele
)eleCol0
“失去参考”。我所说的“失去参考”是指它们既不指向元素也不等于什么。
这就是变量(ele0
和)在局部变量窗口中的显示ele
方式:eleCol0
这是一些代码:
Option Explicit
Public Sub Get_data()
Dim frmDocDap As HTMLDocument, frmDocPlir As HTMLDocument
Dim ele0 As HTMLHtmlElement, ele As HTMLHtmlElement, ele2 As HTMLHtmlElement, ele3 As HTMLHtmlElement
Dim frm As HTMLFrameElement
Dim eleCol As IHTMLElementCollection, eleCol2 As IHTMLElementCollection, eleCol0 As IHTMLElementCollection
Dim i As Integer, j As Integer
Dim sTemp As String
Dim sArr() As String
Dim bFlag As Boolean
Dim iRow As Long
Dim wsHid As Worksheet
'get doc from a frame:
Set frm = html.getElementById("tabIframe2") 'html is a global variable of type HTMLDocument that holds the current IE document.
Set frmDocDap = frm.contentWindow.Document
'udf that delays code by specific seconds:
Delay_Code_By 1
'get table:
Set ele0 = frmDocDap.getElementById("multi_record")
'no records check:
If ele0 Is Nothing And frmDocDap.body.Children.Item(6).innerText = "No records." Then
If MsgBox("Close Internet Explorer?", vbQuestion + vbYesNo, "No records!") = 6 Then _
oIE.Quit
GoTo END_HERE
End If
Set ele0 = ele0.FirstChild
'get first row:
Set eleCol0 = ele0.getElementsByTagName("tr")
'get a specific link.
Set ele2 = html.getElementById("describe")
Set ele2 = ele2.getElementsByTagName("a")(5)
i = 2
NEXT_ITEM:
'click record to open details about it.
Set ele = eleCol0(i)
ele.Click
'at this point reference is lost for variables ele0, eleCol0, ele. All the others are OK.
ele2.Click
'...
END_HERE:
Set ele0 = Nothing
Set ele = Nothing
Set ele2 = Nothing
Set frm = Nothing
Set eleCol0 = Nothing
Set frmDocDap = Nothing
End Sub
Public Sub Delay_Code_By(seconds As Integer)
Dim endTime As Date
endTime = DateAdd("s", seconds, Now)
Do While Now < endTime
DoEvents
Loop
End Sub
有人可以解释一下吗:
- 这个奇怪的变量状态是什么意思?
- 为什么或何时发生这种情况?
我需要了解这一点才能避免它。