VBA Excel - IE GetElementByID无法正常工作 - 运行时错误424对象必需

时间:2018-05-08 16:06:35

标签: excel vba excel-vba internet-explorer getelementbyid

我无法使用Excel VBA(Office 2016)来控制IE(版本11)。我需要在表单中的几个字段中输入信息,然后单击几个单选按钮。我已经确定了我需要修改的所有字段的对象ID。我的代码是从几年前我写的成熟代码中复制/修改的,以便在另一个网站上做类似的事情。虽然它今天继续在其他网站上运行,但它在这里不起作用。不幸的是,它是一个专有的网站,所以我无法共享链接,但这里是我的一些代码和网页代码的一部分:

library(data.table)
setDT(advertising_dataset)
cnames <- colnames(advertising_dataset)
advertising_dataset[, lapply(.SD, foo), .SDcols = cnames[cnames != "Region]]

网页HTML代码的屏幕截图

Screenshot of HTML code for webpage

为什么这对一个网站而不是另一个网站有效?

作为补充说明:当我使用

Sample of my code:
Dim IE As Object, objShell As Object, objCollection As Object

' Take control of the webpage:

' Get the page url
URL = "---------"

' Find the correct instance of IE
marker = 0
Set objShell = CreateObject("Shell.Application")
IE_count = objShell.Windows.Count
For X = 0 To (IE_count - 1)
    On Error Resume Next
    my_title = objShell.Windows(X).Document.Title
    my_url = objShell.Windows(X).LocationURL
    If IsEmpty(my_url) Then
        my_url = objShell.Windows(X).Document.Location
    End If

    If my_url Like Left(URL, 45) & "*" Then 'compare to find if the desired web page is already open
        Set IE = objShell.Windows(X)
        marker = 1
        Exit For
    Else
    End If
Next
If marker = 0 Then
    MsgBox ("Webpage not found. Please login manually.")
    Exit Sub
End If
On Error GoTo -1
On Error GoTo 0
' Wait if necessary
Do Until (IE.ReadyState = 4 And Not IE.Busy)
    DoEvents
    Application.StatusBar = "Waiting for Internet Explorer."
Loop
Application.StatusBar = False

' Set objCollection object
Set objCollection = IE.Document.getElementByID("QSHAA5V0GH4LSAO2AI5R2M853SJ5AI") 
' This is the actual ID of one of the fields I need to enter data into (see screenshot below)
' The above line gives the familiar "Runtime error 424 Object Required" error.

它有时会导致收集一个或多个对象,但通常会导致零。一旦我在收藏家中有了我需要的物品,我就很好,但我还没有。

如果你看到我正在犯的错误,我会非常感谢你了解它,因为我现在很困惑。

我有以下图书馆:

Visual Basic For Applications

Microsoft Excel 16.0对象库

OLE自动化

Microsoft Office 16.0对象库

Microsoft Forms 2.0对象库

Microsoft ActiveX数据对象6.1库

Microsoft Internet Controls

Microsoft HTML对象库

*****这是我正在使用的网页的(修改过的)屏幕截图,如果这有帮助的话。 *****

Webpage screenshot

查看屏幕截图,我应该在对象中查找对象吗?在找到子对象(表单上的字段)之前,是否需要找到父对象(网页中的突出表单)?

1 个答案:

答案 0 :(得分:1)

我找到了答案!我应该在上面的图片中发布更多的网络浏览器代码,其他人会在几个小时前找到它。这里有额外的代码:

Larger screenshot of HTML code from webpage

屏幕截图的左上角显示了标记名&#34; iframe&#34; (今天对我来说是新的)。我需要的对象包含在这个iframe对象中。一旦我发现了这一点,我发现this discussion帮助我创建了这行代码:

Set objCollection = IE.Document.getElementsByTagName("iframe")(1).contentDocument.getElementsByTagName("input")

((1)的值是因为我有两个iframe对象而我正在使用第二个。)

有了这个,只需要在集合中查找具有正确ID的对象!

我可以高兴地跳舞!