Run Time Error '91' : Object Variable or With Block not Set

Valiant 1 Reputation point
2021-10-13T10:06:26.257+00:00

I have been using below code and it is giving me an error that is

Run Time Error '91' : Object Variable or With Block not Set

I do not know why. Error appear on this line Set link = ecoll.getElementsByTagName("a")(0)

If someone can provide alternate solution it will be great help. Any help will be appreciated.

140127-image.png

Sub link()
Dim doc As HTMLDocument
Set doc = New HTMLDocument

Dim lastrow As Long  
Dim ecoll As Object  
Dim link As Object  
Dim t As Date  
  
lastrow = Range("A" & Rows.Count).End(xlUp).Row  
  
t = Now()  
  
Dim reqObj As Object  
Set reqObj = CreateObject("MSXML2.XMLHTTP")  
      
For i = 2 To lastrow  
          
    reqObj.Open "GET", "https://www.google.co.in/search?q=" & Cells(i, 1) & "&rnd=" & WorksheetFunction.RandBetween(1, 10000), False  
    reqObj.send  
      
    doc.body.innerHTML = reqObj.responseText  
      
  
    Set ecoll = doc.getElementById("rso")  
    Set link = ecoll.getElementsByTagName("a")(0)  
          
    Cells(i, 2) = link.href  
Next  
  
Set doc = Nothing  
Set reqObj = Nothing  
  
Debug.Print "done" & "Time taken : " & Format(Now() - t, "hh:mm:ss")  
MsgBox "Ellapsed Time - " & Format(Now() - t, "hh:mm:ss")  

End Sub

Developer technologies Visual Basic for Applications
{count} votes

2 answers

Sort by: Most helpful
  1. Viorel 122.6K Reputation points
    2021-10-14T08:19:46.227+00:00

    I think that you should add a loop:

    . . .
    doc.body.innerHTML = reqObj.responseText
    Do While doc.readyState <> "complete"
       DoEvents
    Loop
    . . .
    

    Also make sure that reqObj.responseText really contains the "rso" element. (Check the text manually; sometimes the HTML response is different and you will need a different getElementById etc.).

    0 comments No comments

  2. Valiant 1 Reputation point
    2021-10-15T11:58:59.633+00:00

    Sir i am not an expert but just beginner to VBA.

    My above code was working when i have different data but now its not working with this data

    3P Pty Limited
    BakPhysio
    BD Rowa
    BHC's Can View
    Blooms The Chemist
    5Odyassist Health And Wellness
    Care Pharmaceuticals

    I just want to get the result First search result in Column B using Column A values like below image.

    140844-image.png

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.