VBA 到网站登录

VBA to site login

我尝试使用从

中找到的 VBA 代码

不幸的是我无法访问它,因为 VBA 正在提示一些错误消息。

收到错误VBA 运行 时间错误 '91' 未设置对象变量或 With Block 变量

Sub login()

    Const Url$ = "https://kn.slync.app/login"

    Dim UserName As String
    Dim Password As String
    Dim LoginData As Worksheet

    Set LoginData = ThisWorkbook.Worksheets("Sheet1")
    
    UserName = LoginData.Cells(1, 2).Value
    Password = LoginData.Cells(2, 2).Value

    Dim ie As Object
    Set ie = CreateObject("InternetExplorer.Application")

    With ie

        .navigate Url
        ieBusy ie
        .Visible = True

    Dim oLoging As Object
    Dim oPassword As Object

    Set oLogin = .document.getElementsByName("username")(0)
    Set oPassword = .document.getElementsByName("password")(0)
    
        oLogin.Value = UserName
        oPassword.Value = Password
        .document.forms(0).submit

    End With

End Sub


Sub ieBusy(ie As Object)
    Do While ie.Busy Or ie.readyState < 4
        DoEvents
    Loop
End Sub

已修改,用户名和密码如下图所示 enter image description here

这是下一行收到的错误信息 .getElementsByClassName("ant-row-flex ant-row-flex-center ant-row-flex-middle")(0).Click

enter image description here

登录输入字段没有 name 属性。您要使用 ID:

Set oLogin = ie.document.getElementById("username")
Set oPassword = ie.document.getElementById("password")

确保在尝试设置这些元素之前等待页面加载的时间足够长,因为页面有很多动态内容要加载。

这是您的代码的快速工作重现,其中有一些简化。 我假设您想设置 UserNamePassword 字段然后 submit 它。

由于 QHarr 已经指出 ,您必须使用 getElementById() 而不是 getElementsByName()

Sub login()

    Const Url$ = "https://kn.slync.app/login"

    Dim UserName As String
    Dim Password As String
    Dim LoginData As Worksheet

    Set LoginData = ThisWorkbook.Worksheets("Sheet1")
    
    UserName = LoginData.Cells(1, 2).Value
    Password = LoginData.Cells(2, 2).Value

    Dim ie As Object
    Set ie = CreateObject("InternetExplorer.Application")

    With ie

        .navigate Url
        ieBusy ie
        .Visible = True

        Set document = .document
        
        With document
            .getElementById("username").Value = UserName
            .getElementById("password").Value = Password
            .forms(0).submit
        End With
        
    End With

End Sub


Sub ieBusy(ie As Object)
    Do While ie.Busy Or ie.readyState < 4
        DoEvents
    Loop
End Sub

我知道你现在面临的问题是什么。设置值实际上不会触发具有值的输入。用户名和密码的值仍然被认为是空的。在这种情况下,我们可以使用SendKeys来模拟用户输入,然后输入的事件就会被成功触发。

您可以根据以下代码更改代码:

With document
     .getElementById("username").Focus
     SendKeys (UserName)
     Application.Wait (Now + TimeValue("00:00:01"))
     .getElementById("password").Focus
     SendKeys (Password)
     Application.Wait (Now + TimeValue("00:00:01"))
     .getElementsByClassName("ant-row-flex ant-row-flex-center ant-row-flex-middle")(0).Click
End With

我用假的 username/password 进行测试,现在消息是“无效 username/password”,这表明它有效: