Может ли кто-нибудь помочь с этим скриптом, чтобы понять, почему мой второй сеанс 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
0
Ewize Afreeca 10 Янв 2017 в 19:53

1 ответ

Лучший ответ

Вы не получаете новый объект, когда повторно назначаете ссылку внутри блока With. With ie увеличивает счетчик ссылок для первого ie объекта, который вы создаете, и все, что начинается с почтения внутри блока, относится к этому объекту. Итак, когда вы это сделаете ...

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

Трудно сказать без фактического URL-адреса, но вы, вероятно, ищете что-то более похожее (без очистки после первого вызова):

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
1
Comintern 10 Янв 2017 в 20:18
Это решило проблему. Спасибо за поломку, которая имеет смысл.
 – 
Ewize Afreeca
10 Янв 2017 в 21:32