循环遍历数据行以提交Web表单

时间:2017-04-12 10:31:45

标签: excel vba

    Sub AutoLoadAccounts()

    Dim IE As Object
    Set IE = CreateObject("InternetExplorer.Application")
    IE.Navigate "https://www.urlhere.com/admin/accounts/create"
    IE.Visible = True

    While IE.busy
    DoEvents
    Wend

    IE.Document.All("title").Value = ThisWorkbook.Sheets("sheet1").Range("a1")
    IE.Document.All("names").Value = ThisWorkbook.Sheets("sheet1").Range("b1")
    IE.Document.All("floor").Value = 30
    IE.Document.getElementById("status").selectedindex = 1
    IE.Document.getElementById("email_state").selectedindex = 1
    IE.Document.All("id").Value = ThisWorkbook.Sheets("sheet1").Range("c1")
    IE.Document.All("years").Value = ThisWorkbook.Sheets("sheet1").Range("d1")
    IE.Document.All("submit").Click

End Sub

上面的代码用于填充Web表单并提交。我有大约150行数据,范围从A1:D1。我试图找到一种方法在提交表单后逐行循环遍历行直到它到达结尾。

所以基本上它会从第一行开始并填充A1:D1中的字段,然后一旦完成就进入下一行并对A2执行相同的操作:D2。等等

1 个答案:

答案 0 :(得分:2)

这里的诀窍是整理你的源数据。使用两列,您可以记录字段名称和所需的值:

    A           B
1   Title       Sample Title
2   Names       Sample Names
3   Floor       Sample Floor

循环:

Sub AutoLoadAccounts()

    Dim IE As Object
    Dim cRow As Range       ' Current row, used to extract values from Excel.

    Set IE = CreateObject("InternetExplorer.Application")
    IE.Navigate "https://www.urlhere.com/admin/accounts/create"
    IE.Visible = True

    While IE.busy
    DoEvents
    Wend

    ' Executes once for each row in the source range.
    For Each cRow In ThisWorkbook.Sheets("sheet1").Range("A1:A3")

        ' Read field name and value from current row.
        IE.Document.All(cRow.Value).Value = cRow.Offset(0, 1)
    Next


    IE.Document.All("submit").Click
End Sub

此代码可以改进。目前,源范围是硬编码的(Range("A1:A3"))。您可以改进这一点,因此代码会自动识别Excel中所有已完成的行。如果您有兴趣研究工作表UsedRange object

修改
添加了从列而不是行读取源数据的示例。

Sub AutoLoadAccounts_Columns()

    Dim IE As Object
    Dim cRow As Range       ' Current row, used to extract values from Excel.

    Set IE = CreateObject("InternetExplorer.Application")
    IE.Navigate "https://www.urlhere.com/admin/accounts/create"
    IE.Visible = True

    While IE.busy
    DoEvents
    Wend

    ' Executes once for each row in the source range.
    For Each cRow In ThisWorkbook.Sheets("sheet1").Range("A1:C1")

        ' Read field name and value from current row.
        IE.Document.All(cRow.Value).Value = cRow.Offset(1, 0).Value
    Next


    IE.Document.All("submit").Click
End Sub