关于excel:getElementById在VBA中不起作用,错误438

getElementById won't work in VBA, error 438

我在VBA相对较新(我了解基本知识,但其他知识不多),并且我试图建立一些代码来为我填写在线表单,但是当我运行代码时,出现438错误:

object doesnt support this property or method

到达

1
ie.document.getElementById ("q")

我已将HTML对象库和Microsoft Internet控件添加到我的引用中。我看了很多在线论坛。我什至将整个脚本直接复制并粘贴到VBA中。没有什么可以使它使用getElementById()。这是我的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Sub internetstuff()

Dim ie As Object

Set ie = CreateObject("internetexplorer.application")

ie.Visible = True

ie.navigate ("https://www.google.com/")

Set searchbx = ie.document.getElementById("q")

searchbx.Value ="Howdy!"

End Sub

应该发生的是,它应该打开InternetExplorer,转到Google,然后在搜索栏中填充" Howdy!"。
相反,它仅打开google,然后我收到错误消息,并且它停止运行。


因为"q"不是ID,所以它是Name

您必须使用GetElementsByName并选择第一个元素

尝试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Sub internetstuff()

Dim ie As Object

Set ie = CreateObject("internetexplorer.application")

ie.Visible = True

ie.Navigate ("https://www.google.com/")

    Do Until ie.ReadyState >= 4
        DoEvents
    Loop


Set searchbx = ie.document.getElementsByName("q")(0)

searchbx.Value ="Howdy!"

End Sub

我还添加了一个等待事件,以防加载Google花费时间。

结果:

enter


一种更简洁有效的方法是使用querySelector返回name属性的第一个匹配项

1
2
3
4
5
6
7
8
9
10
11
12
13
Option Explicit
Public Sub internetstuff()
    Dim ie As Object
    Set ie = CreateObject("InternetExplorer.Application")
    With ie
        .Visible = True
        .Navigate2"https://www.google.com/"
        While .Busy Or .readyState < 4: DoEvents: Wend
        .document.querySelector("[name=q]").Value ="Howdy"
         Stop '<delete me later
        .Quit
    End With
End Sub