Excel VBA script to prefill online form using IE?

2019-04-13 03:37发布

问题:

I am in need of assistance. I am trying to write a VBA script that would take the value in column A and place it on an online form in an input element with no ID but the name ("OldUrl"). Then the VBA script would take the value in the adjacent cell in column B and place that in the same form ("digiSHOP") in the input field named ("NewUrl").

The form is on a secure server however I have gotten as far as the window pulling up and the form selected. I am having trouble finding a way to target the input field since they have no ID. Below is my code and thank you for your help.

Sub Redirect()
Dim IE As Object
Dim doc As Object
Dim form As Object
Dim OldURL As Object
Dim NewURL As Object

Set IE = CreateObject("InternetExplorer.Application")

With IE
    .Visible = True
    .Navigate "https://...."

    Do Until .ReadyState = 4: DoEvents: Loop

    Set doc = IE.Document
    Set form = doc.forms("digiSHOP")
    Set OldURL = doc.getElementById("OldUrl")'Error occurs here. Element has no ID
    OldURL.Value = Range("A2")
    Set NewURL = doc.getElementById("NewUrl")
    NewURL.Value = Range("B2")
    form.submit

    Do Until .ReadyState = 4: DoEvents: Loop
    Do While .Busy: DoEvents: Loop

    End With
End Sub

Also I wasn't sure how to target the entire column and loop it therefore the Value is set to the cell A2. This was more to test the script.

回答1:

Sub Redirect()
Dim IE As Object
Dim doc As Object

    Set IE = CreateObject("InternetExplorer.Application")

    With IE
        .Visible = True
        .Navigate "https://...."

        Do Until .ReadyState = 4: DoEvents: Loop

        With .Document.forms("digiSHOP")
            .elements("OldUrl").Value = Range("A2")
            .elements("NewUrl").Value = Range("B2")
            .submit
        End With

        Do Until .ReadyState = 4: DoEvents: Loop
        Do While .Busy: DoEvents: Loop

    End With
End Sub