1

I have a code to navigate to a website and fill up a form with 33 inputs.

This is the code:

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

Now, this works like a charm. Not a single error.

The input 1 receives "Test 1"; The input 2 receives "Test 2"; ... ; The input 33 receives "Test 33";

But, the actual data that i need to pass is in my worksheet in the range AI43:AI75

If i change this part

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

To this

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

The output, each time is different, and always wrong. The order of the inputs go crazy and some inputs stay blank.

Example: input 1 receives "data 1", input 2 receives "data 2", input 3 receives "data 30", input 4 receives nothing, input 5 receives "data 10".

And eachtime i run it, the output is different. Any ideas why? Can't figure it out.

K.Dᴀᴠɪs
  • 9,945
  • 11
  • 33
  • 43
Guilherme
  • 161
  • 3
  • 14

1 Answers1

1

Instead of using your For i = ... statement, see if a For Each statement would do what you need by iterating through the collection itself.

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
K.Dᴀᴠɪs
  • 9,945
  • 11
  • 33
  • 43
  • @RyanWildry Updated answer – K.Dᴀᴠɪs Feb 01 '18 at 01:31
  • @K.Davis it didn't work. I think the problem is in the lenght of my cells. My range have cells with 200+ caracters. When i changed the cells to 10 caracters at most, it worked just fine. Can't figure it out why. I'm running out of options – Guilherme Feb 01 '18 at 12:39
  • @K.Davis Thankkk you so much!!! It did work. I was trying with a different code. Using "For Each o" instead of "For i = 0 To objCollection.Lenght" doesn't let the program get lost. Dunno why, but it worked. I'll update the post with the answer – Guilherme Feb 01 '18 at 12:47
  • @Guilherme There's no need to update your question with the answer. Simply mark this one as accepted. – K.Dᴀᴠɪs Feb 01 '18 at 14:44