VBA IE 自动化 - 在网页上单击按钮时,元素变量失去引用

VBA IE automation - variable for element loses reference when button clicked on webpage

我使用 VBA 和 IE 自动化打开网页,登录,通过填写一些输入字段并单击网页的特定按钮进行导航,最后从中获取一些数据。

在导航时,我为网页中的元素设置了几个变量。接下来,我单击网页按钮,然后单击一些变量(ele0eleeleCol0)“丢失引用”。 “丢失引用”是指它们既不指向元素也不等于任何元素。


这就是变量ele0eleeleCol0在局部变量Window:


下面是一些代码:

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

有人可以解释一下吗:

我需要了解这一点才能避免它。

您经常会在刷新时遇到过时的元素,例如某些点击事件。如果元素存在于新加载的内容中,那么通常可以简单地避免存储在变量中并始终关闭 ie.document.. 我假设您正在使用一个实时文档,该文档可以根据您执行的操作进行更新。然后我会在本地传递 Internet Explorer 实例,而不是在全局传递存储的 HTMLDocument 变量。