1

我有一个代码可以导航到一个网站并填写一个包含 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接收“Test 1”;输入2接收“Test 2”;... ; 输入33接收“Test 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”。

每次我运行它,输出都是不同的。任何想法为什么?想不通。

4

1 回答 1

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
于 2018-01-31T23:15:45.790 回答