2016-04-27 154 views
1

我有大約12,000行數據,我需要的網站。這個VBA代碼工作正常約800,然後停下來。現在由於這個錯誤我無法再次運行。我無法弄清楚如何讓它再次運行。VBA運行時錯誤'91'對象變量或塊變量未設置

運行時錯誤「91」對象的變量或帶塊變量未設置

Sub XMLHTTP() 

    Dim url As String, lastRow As Long 
    Dim XMLHTTP As Object, html As Object, objResultDiv As Object, objH3 As Object, link As Object 
    Dim start_time As Date 
    Dim end_time As Date 

    lastRow = Range("A" & Rows.Count).End(xlUp).Row 

    Dim cookie As String 
    Dim result_cookie As String 

    start_time = Time 
    Debug.Print "start_time:" & start_time 

    For i = 2 To lastRow 

     url = "https://www.google.co.in/search?q=" & Cells(i, 1) & "&rnd=" & WorksheetFunction.RandBetween(1, 10000) 

     Set XMLHTTP = CreateObject("MSXML2.serverXMLHTTP") 
     XMLHTTP.Open "GET", url, False 
     XMLHTTP.setRequestHeader "Content-Type", "text/xml" 
     XMLHTTP.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:25.0) Gecko/20100101 Firefox/25.0" 
     XMLHTTP.send 

      Set html = CreateObject("htmlfile") 
     html.body.innerHTML = XMLHTTP.ResponseText 
     Set objResultDiv = html.getelementbyid("rso") 
     Set objH3 = objResultDiv.getelementsbytagname("H3")(0) 
     Set link = objH3.getelementsbytagname("a")(0) 


     str_text = Replace(link.innerHTML, "<EM>", "") 
     str_text = Replace(str_text, "</EM>", "") 

     Cells(i, 2) = str_text 
     Cells(i, 3) = link.href 
     DoEvents 
    Next 

    end_time = Time 
    Debug.Print "end_time:" & end_time 

    Debug.Print "done" & "Time taken : " & DateDiff("n", start_time, end_time) 
    MsgBox "done" & "Time taken : " & DateDiff("n", start_time, end_time) 
End Sub 
+0

'URL = 「https://www.google.co.in/search?q=」 &細胞(I,1)& 「&RND =」 &WorksheetFunction.RandBetween(1,10000) '你在破解網站嗎? – findwindow

+0

我不知道你的意思是「破解網站」 我應該提到,我從這個網頁找到了這段代碼:http://stackoverflow.com/questions/17495644/using-vba-in-excel-to- google-search-in-ie-and-return-the-first-of-the-first – Brayheart

+0

你在谷歌搜索隨機頁面(RandBetween)12k次。這是餅乾做的事情。只是想確定。 – findwindow

回答

1

運行時錯誤「91」對象的變量或帶塊變量未設置

您正在收到該錯誤,因爲下面的SET語句之一失敗。

Set objResultDiv = html.getelementbyid("rso") 
Set objH3 = objResultDiv.getelementsbytagname("H3")(0) 
Set link = objH3.getelementsbytagname("a")(0) 

您需要正確處理對象。例如

Set objResultDiv = HTML.getelementbyid("rso") 

If objResultDiv Is Nothing Then 
    MsgBox "Id `rso` not found for " & Cells(i, 1) 
Else 
    Set objH3 = objResultDiv.getelementsbytagname("H3")(0) 

    If objH3 Is Nothing Then 
     MsgBox "Tag `H3` not found for " & Cells(i, 1) 
    Else 
     Set link = objH3.getelementsbytagname("a")(0) 

     If link Is Nothing Then 
      MsgBox "Tag `a` not found for " & Cells(i, 1) 
     Else 
      ' 
      '~~> Rest of your code 
      ' 
     End If 
    End If 
End If 
相關問題