【发布时间】:2018-05-08 16:06:34
【问题描述】:
我无法让 Excel VBA (Office 2016) 控制 IE(版本 11)。我需要在表单的几个字段中输入信息,然后单击几个单选按钮。我已经确定了我需要修改的所有字段的对象 ID。我的代码是从我几年前编写的成熟代码中复制/修改的,以便在另一个网站上做类似的事情。虽然它今天继续在其他网站上运行,但它在这里不起作用。不幸的是,它是一个专有网站,所以我无法分享链接,但这里是我的一些代码和部分网页代码:
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.
网页 HTML 代码截图
为什么这适用于一个网站而不适用于另一个网站?
补充说明:当我使用
Set objCollection = IE.Document.getElementsByClassName("Class")
MsgBox objCollection.Length
它有时会导致收集一个或多个对象,但通常会导致零。一旦我在收集器中获得了我需要的对象,我就很好了,但我还没有。
如果您发现我犯了一个错误,我将非常感谢您了解它,因为我现在很困惑。
我包含以下库:
Visual Basic 应用程序
Microsoft Excel 16.0 对象库
OLE 自动化
Microsoft Office 16.0 对象库
Microsoft Forms 2.0 对象库
Microsoft ActiveX 数据对象 6.1 库
微软互联网控制
Microsoft HTML 对象库
***** 这是我正在使用的网页的(修改后的)屏幕截图,如果有帮助的话。 *****
看截图,我应该在对象中寻找对象吗?是否需要先找到父对象(网页中突出的表单)才能找到子对象(表单上的字段)?
【问题讨论】:
-
看你有限的代码,如果你不匹配URL,你永远不会创建IE对象。如果您的 IE 对象未设置,它很可能会抛出该错误。你能在该行放一个断点并检查 IE 对象是否已设置并指向 wright IE 会话?
-
好问题。我使用 [ MsgBox URL & Chr(10) & my_url ] 检查并验证 URL 完全匹配。
-
好的,但是IE对象设置是否符合预期?
-
另外,我在 [ Set IE = objShell.Windows(X) ] 之后验证了 IE 设置为“Internet Explorer”(它的正确会话)。
-
如果有帮助的话,我添加了修改后的网页截图。
标签: vba excel internet-explorer getelementbyid