无法使用VBA登录多个页面

时间:2017-01-10 16:53:04

标签: excel vba excel-vba

任何人都可以协助使用此脚本来查看为什么我的第二个IE会话启动但密码和用户的输入数据没有填充。

Sub MyLogin()
Dim Url As String
Dim ie As Object

    Set ie = CreateObject("InternetExplorer.Application")
    With ie
        .Visible = True
        .navigate "https://website"

        Do Until .readystate = 4
            DoEvents
        Loop

        .document.all.Item("username").Value = "userid"
        .document.all.Item("password").Value = "password//"
        .document.forms(0).submit

        Url = "https://website"
        Set ie = CreateObject("InternetExplorer.Application")
        ie.Visible = True
        ie.navigate Url
        ie = Nothing

        Do
        DoEvents
        Loop Until ie.readystate = 4

        .document.all.Item("Enter user name").Value = "userid"
        .document.all.Item("passwd").Value = "password"
        .document.forms(0).submit

    End With
End Sub

1 个答案:

答案 0 :(得分:1)

With块内重新分配引用时,您不会获得新对象。 With ie会增加您创建的第一个 ie对象的引用计数,并且以块内的deference开头的所有内容都指的是该引用计数。所以,当你这样做时......

Set ie = CreateObject("InternetExplorer.Application")

...来自 With块,以下代码行......

    .document.all.Item("Enter user name").Value = "userid"
    .document.all.Item("passwd").Value = "password"
    .document.forms(0).submit

...都引用了您创建的第一个InternetExplorer.Application对象(由With ie引用的对象)。

此代码演示了此处发生的事情(使用Scripting.Dictionary进行说明):

Sub FooedUp()
    Dim foo As Scripting.Dictionary
    Set foo = New Scripting.Dictionary
    With foo                      'This now holds a reference to the 'foo' above.
        Debug.Print ObjPtr(foo)   'This is the pointer to that instance.
        .Add 1, 1                 'Add an item.
        Debug.Print .Count        'Count is now 1`.
        Set foo = New Scripting.Dictionary   'Re-use the 'foo' variable.
        Debug.Print ObjPtr(foo)   'The pointer is now different.
        Debug.Print .Count        '...but this is still bound to the first 'foo', prints 1.
    End With
End Sub

很难说没有实际的网址,但你可能正在寻找更像这样的东西(减去第一次调用后的清理):

Sub MyLogin()
    Dim Url As String
    Dim ie As Object

    Set ie = CreateObject("InternetExplorer.Application")
    With ie
        .Visible = True
        .navigate "https://website"
        Do Until .readystate = 4
            DoEvents
        Loop
        .document.all.Item("username").Value = "userid"
        .document.all.Item("password").Value = "password//"
        .document.forms(0).submit
    End With   '<--Un-bind the first IE object.

    Url = "https://website"
    Set ie = CreateObject("InternetExplorer.Application")
    ie.Visible = True
    ie.navigate Url
    With ie    '<--Bind the new IE object.
        Do
            DoEvents
        Loop Until ie.readystate = 4
        .document.all.Item("Enter user name").Value = "userid"
        .document.all.Item("passwd").Value = "password"
        .document.forms(0).submit
    End With
End Sub