IE自动化问题

时间:2018-01-31 21:33:05

标签: excel vba excel-vba ie-automation

我有一个代码可以导航到一个网站并填写一个包含33个输入的表单。

这是代码:

Dim i As Long
Dim IE As Object
Dim objCollection As Object

Set IE = CreateObject("InternetExplorer.Application")

IE.Visible = True

IE.Navigate "https://mylink.com"

Do While IE.Busy: DoEvents: Loop
Do While IE.ReadyState <> 4: DoEvents: Loop

Set objCollection = IE.Document.getElementsByTagName("input")

For i = 0 To objCollection.Length
objCollection(i).innertext = "Test " & i
Next i

Set IE = Nothing
Set objElement = Nothing
Set objCollection = Nothing

现在,这就像一个魅力。没有一个错误。

  

输入1接收“测试1”;输入2接收“测试2”; ......;   输入33接收“测试33”;

但是,我需要传递的实际数据是在AI43:AI75范围内的工作表中

如果我改变这部分

 For i = 0 To objCollection.Length
objCollection(i).innertext = "Test " & i
Next i

到此

j = 1
For i = 0 To objCollection.Length
objCollection(i).innertext = Range("AI" & 42 + j).Text
j = j + 1
Next i

输出,每次都不同,总是错误的。输入的顺序变得疯狂,一些输入保持空白。

  

示例:输入1接收“数据1”,输入2接收“数据2”,输入3   接收“数据30”,输入4什么都不接收,输入5接收“数据”   10" 。

每次我运行它,输出都不同。有什么想法吗?无法理解。

1 个答案:

答案 0 :(得分:1)

不要使用For i = ...语句,而是通过迭代集合本身来查看For Each语句是否能满足您的需要。

Dim IE As Object, i as Long
Dim objCollection As Object, o As Object  '  <--- New declaration

Set IE = CreateObject("InternetExplorer.Application")

IE.Visible = True

IE.navigate "https://mylink.com"

Do While IE.Busy: DoEvents: Loop
Do While IE.readyState <> 4: DoEvents: Loop

Set objCollection = IE.document.getElementsByTagName("input")

For Each o In objCollection
    i = i + 1
    o.innerText = "Test " & i
Next o

Set IE = Nothing
Set objElement = Nothing
Set objCollection = Nothing