VBA 单击 IE 表单上的按钮进行提交

VBA to click on a button on an IE form to submit it

我是 VBA 的新手,所以请多多包涵。我一直在尝试创建一个自动化来填写用户名和密码并登录到一个网站(首先),但我一直无法尝试点击提交按钮。搜索了互联网并学到了很多东西,但我没有找到任何似乎有用的东西。页面加载并填写详细信息,当我 运行 下面的代码时没有任何反应。

非常感谢对此的一些帮助。一如既往地提前致谢!

Sub worldcheck()

Dim lastrow As Long
Dim IE As Object
Dim cel As Range
Dim post As Object
Dim ws As Worksheet
Dim element As Object

Set ws = Sheets("sheet1")
Set IE = CreateObject("internetexplorer.application")
lastrow = ws.Range("B" & ws.Rows.Count).End(xlUp).Row

IE.Visible = True
IE.Navigate "https://www.world-check.com/frontend/login/"

Do While IE.busy
    DoEvents
Loop

Application.Wait (Now + TimeValue("0:00:2"))

IE.document.getElementbyID("username").Value = ws.Range("D2")
IE.document.getElementbyID("password").Value = ws.Range("D3")
IE.document.getElementbyClass("button").click

Do While IE.busy
    DoEvents
Loop

End Sub

没有其他事情发生?当您尝试使用不存在的方法时,您至少应该收到一条错误消息(VBA 运行-time error 438 Object doesn't support this 属性 或方法 ) 。该方法是 getElementsByClassName - 注意 s 表示它 returns 是一个集合,结尾是 ClassName。然后,在尝试访问 Click 方法

之前,您需要对该集合进行索引

因为只有一个元素具有类名 button,所以您可以使用更快的 css class selector (this is also faster than using a type selector of form; likewise, you can use the faster css equivalent of getElementById for the other two DOM elements). document.querySelector 在第一个匹配处停止,这样效率也更高。

最后,不要硬编码等待,而是使用正确的页面加载等待,如下所示:

Option Explicit

Public Sub WorldCheck()
    Dim ie As Object

    Set ie = CreateObject("InternetExplorer.Application")

    With ie

        .Visible = True
        .Navigate2 "https://www.world-check.com/frontend/login/"

        While .busy Or .readystate <> 4: DoEvents: Wend

        With .document
            .querySelector("#username").Value = "ABCDEF" ' equivalent to .getElementbyID("username").Value = "ABCDEF"
            .querySelector("#password").Value = "GHIJKL" '.getElementbyID("password").Value = "GHIJKL"
            .querySelector(".button").Click
        End With

        While .busy Or .readystate <> 4: DoEvents: Wend

            Stop                                     '<== delete me later
        .Quit
    End With
End Sub